Skip to main content

useIntersection

Tracks an HTML element's intersection using Intersection Observer API.

info

One of the most common cases where this hook is used is when you create a page with infinite-scroll.

tip

In some cases, it may be better to use useInView because it is simpler.


API​

const ref = useIntersection({
onIntersect,
onEnter,
onLeave,
enabled,
root,
rootMargin,
threshold,
});

Options​

  • onIntersect?: (isIntersecting: boolean, entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on enter & on leave
  • onEnter?: (entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on enter
  • onLeave?: (entry?: IntersectionObserverEntry) => void
    • Defaults to () => {}
    • Callback fired on leave
  • enabled?: boolean
    • Defaults to true
    • Determine whether intersection observer should be enabled or not
  • root?: Element | Document
    • Defaults to the browser viewport if not specified or if null
    • The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target
  • rootMargin?: string
    • Defaults to all zeros
    • Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left), the values can be percentages
  • threshold?: number
    • Defaults to 0
    • Indicate at what percentage of the target's visibility the observer's callback should be executed

Returns​

  • ref: React.MutableRefObject
    • The ref used on JSX element

Examples​

http://localhost:3000/
ℹī¸ Scroll and check console
Element A
import { useIntersection } from 'react-power-ups';

export function Demo() {
const refA = useIntersection({
onEnter: () => console.log('Element A appeared in page'),
onLeave: () => console.log('Element A dissappeared from page'),
});

const refB = useIntersection<HTMLTextAreaElement>({
threshold: 0.5,
onIntersect: (isIntersecting, entry) => {
console.log('onIntersect triggered', isIntersecting, entry);
},
});

return (
<>
<div style={{ height: 1000 }} />

<div ref={refA} className="bg-slate-500">
Element A
</div>

<div style={{ height: 1000 }} />

<textarea ref={refB} defaultValue="Element B (with threshold: 0.5)" />

<div style={{ height: 1000 }} />
</>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-intersection.ts