Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve useInViewObserver hook to trigger when observer is in view on mount #18446

Merged
merged 1 commit into from
Jan 2, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading