Skip to content
Mosaic
On this page

useInView

Tracks whether an element intersects its root with an IntersectionObserver. Attach the returned ref to the element.

Use for

  • loading the next page when the end of a list scrolls into view
  • reacting when an element becomes visible

Practices

GuidancePractice
Don’tRely on triggerOnce. The type accepts it, but the hook does not read it and keeps observing.

Options

PropTypeDescription
rootElement | Document | nullThe element used as the viewport. The browser viewport when unset.
rootMarginstringGrows or shrinks the root box before computing intersections.
thresholdnumber | number[]Ratio or ratios of visibility the element must reach to count as in view. Read when the ref attaches.Default: 0
onChange(inView: boolean, entry: IntersectionObserverEntry) => voidCalled with inView and the entry on every observer callback.

Returns

PropTypeDescription
inViewbooleanWhether the element last reported as intersecting at or above a threshold.Default: false
ref(element: HTMLElement | null) => voidCallback ref to attach to the observed element. Disconnects when the element detaches.

Examples

Load more at the end of a list

TSX
const { ref } = useInView({
  threshold: 0,
  onChange: inView => {
    if (inView) void fetchNext();
  },
});

<div ref={ref} />