useIntersection Hook
Diego Muralles avatar
Written by Diego Muralles
Updated over a week ago

Tracks the portion of an element that intersects with the visible area of the screen (the viewport).

Usage

const el_intersection: false | IntersectionObserverEntry = useIntersection(ref: React.RefObject, options?: IObserverOptions);

Relevant Interfaces

interface IntersectionObserverEntry {
//properties of the tracked reference element
boundingClientRect: DOMRectReadOnly;
//visible amount of the tracked reference element
intersectionRatio: number;
//properties of only the visible portion of the tracked reference element (a subset of boundingClientRect)
intersectionRect: DOMRectReadOnly;
isIntersecting: boolean;
rootBounds: DOMRectReadOnly | null;
target: Element;
time: number;
}

interface IObserverOptions {
//number of times the hook updates as the tracked element enters the visible screen. Defaults to 1.
steps?: number;
//decimal values indicating the intersection percentage at which the hook updates.
threshold?: number[];
}

It is not possible to define both a step and a threshold. Define one at most.

Example

Display the percentage of a widget that intersects with the viewport. Update this value 10 times over the course of the widget’s entrance into the viewport.

import { useRef } from 'react';
import { useIntersection } from 'vev';

export default function() {
const widgetReference = useRef(null);
const intersection = useIntersection(widgetReference, {steps: 10});

return (
<div className="fill" ref={widgetReference}>
<h1>{ (intersection.intersectionRatio)*100 }</h1>
</div>
);
}

Did this answer your question?