From 62010e35be4cdb9c46fb0bd90cb26073e9237f5b Mon Sep 17 00:00:00 2001 From: CH Date: Thu, 2 Jan 2025 16:42:12 +0700 Subject: [PATCH] fix: improve useInViewObserver hook to trigger when observer is already in view on mount --- packages/lib/hooks/useInViewObserver.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/lib/hooks/useInViewObserver.ts b/packages/lib/hooks/useInViewObserver.ts index 7396f2be46952d..6e3954daf95d85 100644 --- a/packages/lib/hooks/useInViewObserver.ts +++ b/packages/lib/hooks/useInViewObserver.ts @@ -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( @@ -35,7 +40,7 @@ export const useInViewObserver = (onInViewCallback: () => void, root?: Element | observer.disconnect(); } }; - }, [node]); + }, [onInViewCallback, node]); return { ref: setRef,