useOnScreen

useOnScreen

The useOnScreen hook is a custom React hook designed to determine whether a specified element is currently visible on the screen or not. It leverages the Intersection Observer API to observe changes in the element's intersection with the viewport and provides a boolean value indicating its visibility status.

Props

The useOnScreen hook takes a single parameter:

  • ref (RefObject<Element | null>): A React ref object that references the DOM element to be observed. It can be created using the useRef hook.

Returns

The useOnScreen hook returns a boolean value that indicates whether the observed element is currently visible on the screen (true) or not (false).

The Hook

useOnScreen.ts
import { useEffect, useMemo, useState, RefObject } from "react";
 
export function useOnScreen(ref: RefObject<HTMLElement | null>) {
  const [isIntersecting, setIntersecting] = useState(false);
 
  const observer = useMemo(
    () =>
      new IntersectionObserver(([entry]) =>
        setIntersecting(entry.isIntersecting)
      ),
    [ref]
  );
 
  useEffect(() => {
    if (ref.current) {
      observer.observe(ref.current);
    }
    return () => observer.disconnect();
  }, []);
 
  return isIntersecting;
}

Usage

UseOnScreenDemo.tsx
import React, { useRef } from "react";
import { useOnScreen } from "./useOnScreen";
 
export const UseOnScreenDemo = () => {
  const elementRef = useRef<HTMLDivElement | null>(null);
  const isElementOnScreen = useOnScreen(elementRef);
 
  return (
    <div>
      <div style={{ height: "100vh" }}>Scroll down to see the effect</div>
      <div
        ref={elementRef}
        style={{
          height: "100px",
          background: isElementOnScreen ? "green" : "red",
        }}
      >
        This element turns green when it's on the screen.
      </div>
    </div>
  );
};