react-on-screen
Replacing react-on-screen useOnScreen()
Vanilla JavaScript
import { useState, useEffect } from "react";
export function useOnScreen(ref, rootMargin = "0px") {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting),
{ rootMargin }
);
if (ref.current) observer.observe(ref.current);
return () => observer.disconnect();
}, [ref, rootMargin]);
return isIntersecting;
}
Why Use This?
Calculating scroll boundaries manually or listening to `scroll` events used to cripple browser performance due to layout thrashing. The `IntersectionObserver` API resolves this elegantly by shifting the computation off the main thread natively.