Skip to the content

useIntersect

useIntersect calls a function whenever an element enters its root (the viewport by default), using IntersectionObserver. Use it for infinite scroll sentinels, lazy loading and view tracking.
Hooks

Signature

const [setNode] = useIntersect(options: IntersectionObserverInit, onIntersect?: () => void);
Name
Type
Description
options
IntersectionObserverInit
root (default null), rootMargin (default '0px'), threshold (default 0.5).
onIntersect
() => void
Runs each time the element becomes visible. Always the latest version runs.
returns
[setNode]
A callback ref: pass it as the observed element's ref.
Scrolls sideways inside the table. The page does not.

Example

import { useIntersect } from '@apollion-dsi/core/hooks';

function LoadMore({ onVisible }: { onVisible: () => void }) {
  const [setNode] = useIntersect({ threshold: 1 }, onVisible);

  return <div ref={setNode}>Loading more…</div>;
}

Pitfalls

  • It fires on every entry, not once. Guard the callback (an isLoading flag) if it must not repeat.
  • An inline threshold array is a new value on every render and rebuilds the observer each time. Hoist it.
  • Without IntersectionObserver, the callback runs once on mount, as if the element were visible.

See also