React hook for check when component is visible
Posted
•
Updated
1import { useEffect, useState } from "react";
2
3export function useIsVisible(ref) {
4 const [isIntersecting, setIntersecting] = useState(false);
5
6 useEffect(() => {
7 const observer = new IntersectionObserver(([entry]) => {
8 setIntersecting(entry.isIntersecting)
9 }
10 );
11
12 observer.observe(ref.current);
13 return () => {
14 observer.disconnect();
15 };
16 }, [ref]);
17
18 return isIntersecting;
19 }