Function useOnScreen

  • Custom React hook to detect when an element is visible in the viewport. Uses the Intersection Observer API.

    Parameters

    • ref: RefObject<HTMLElement>

      Reference to the target element.

    • Optionalratio: number = 1.0

      Visibility ratio threshold (between 0.0 and 1.0).

    Returns boolean

    • true if the element is visible based on the given ratio, false otherwise.

    If ratio is not between 0.0 and 1.0.

    // Basic usage: Check if an element is fully visible
    const ref = useRef(null);
    const isVisible = useOnScreen(ref);

    <div ref={ref}>This element is {isVisible ? "visible" : "not visible"}</div>;
    // Check if an element is at least 50% visible
    const ref = useRef(null);
    const isHalfVisible = useOnScreen(ref, 0.5);