• Custom React hook that observes whether a specified element is within the visible area (viewport).

    This hook uses the Intersection Observer API to monitor the visibility of an element. It provides callbacks for when the element enters or exits the viewport, and can optionally destroy the observer when the element enters the viewport for the first time.

    Example

    const MyComponent = () => {
    const ref = useRef<HTMLDivElement>(null);

    const { state } = useInViewport({
    ref,
    onIn: () => console.log('Element is in the viewport!'),
    onOut: () => console.log('Element is out of the viewport!'),
    });

    return <div ref={ref}>Observe me! State: {state}</div>;
    };

    Parameters

    Returns {
        state: undefined | "in" | "out";
    }

    • state: undefined | "in" | "out"