-
Notifications
You must be signed in to change notification settings - Fork 0
/
useOnScreen.ts
38 lines (29 loc) · 1.24 KB
/
useOnScreen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useEffect, useState, RefObject } from 'react';
/**
* A custom React hook that detects whether an element is within the viewport.
* @param ref A reference to the DOM element to observe.
* @param rootMargin The margin around the root (viewport) within which to trigger visibility.
* @returns A boolean indicating whether the observed element is visible in the viewport.
*/
const useOnScreen = (ref: RefObject<Element>, rootMargin: string = '0px'): boolean => {
// Initialize state to track visibility
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
// Check if the ref is available
if (ref.current == null) return;
// Create an IntersectionObserver instance
const observer = new IntersectionObserver(([entry]) => setIsVisible(entry.isIntersecting), { rootMargin });
// Observe the target element
observer.observe(ref.current);
// Cleanup function to disconnect the observer when unmounting or ref changes
return () => {
if (ref.current == null) return;
observer.unobserve(ref.current);
};
}, [ref, rootMargin]);
return isVisible;
};
export default useOnScreen;
// Example usage
// const headerTwoRef = useRef()
// const visible = useOnScreen(headerTwoRef, "-100px")