Build a Custom useIntersectionObserver Hook
3 minintermediatereactcodingcustomuseintersectionobserverhook
Quick Answer
Implement a hook that tracks when an element enters/exits the viewport with proper TypeScript typing.
Detailed Answer
Build a Custom useIntersectionObserver Hook
Implement a hook that tracks when an element enters/exits the viewport with proper TypeScript typing.
Solution:
function useIntersectionObserver(
options: IntersectionObserverInit = {}
): [React.RefObject<HTMLElement>, IntersectionObserverEntry | null] {
const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => setEntry(entry),
options
);
observer.observe(element);
return () => observer.disconnect();
}, [options]);
return [ref, entry];
}
// Usage
const MyComponent = () => {
const [ref, entry] = useIntersectionObserver({
threshold: 0.5,
rootMargin: '0px'
});
return (
<div ref={ref}>
{entry?.isIntersecting ? 'Visible' : 'Hidden'}
</div>
);
};