useOnScreen

Hook to get whether a element (via ref) is visible (intersecting) on screen.

Install all hooks via:

npm install @styple/hooks

or copy the source:

import { useState, useEffect, MutableRefObject } from "react";
export const useOnScreen = (ref: MutableRefObject<Element | null>) => {
const [isIntersecting, setIntersecting] = useState<boolean>(false);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) =>
setIntersecting(entry.isIntersecting)
);
if (ref.current) observer.observe(ref.current);
// Remove the observer as soon as the component is unmounted
return () => {
observer.disconnect();
};
}, [ref]);
return isIntersecting;
};