Skip to content

Commit

Permalink
fix: improve useInViewObserver hook to trigger when observer is alrea…
Browse files Browse the repository at this point in the history
…dy in view on mount
  • Loading branch information
cnhhoang850 committed Jan 2, 2025
1 parent fec5044 commit 62010e3
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/lib/hooks/useInViewObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export const useInViewObserver = (onInViewCallback: () => void, root?: Element |
return;
}

if (node && node.getBoundingClientRect().top < window.innerHeight) {
// Trigger callback immediately if element is already in view on mount
onInViewCallback();
}

let observer: IntersectionObserver;
if (node && node.parentElement) {
observer = new IntersectionObserver(
Expand All @@ -35,7 +40,7 @@ export const useInViewObserver = (onInViewCallback: () => void, root?: Element |
observer.disconnect();
}
};
}, [node]);
}, [onInViewCallback, node]);

return {
ref: setRef,
Expand Down

0 comments on commit 62010e3

Please sign in to comment.