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
| Guidance | Practice |
|---|---|
| Don’t | Rely on triggerOnce. The type accepts it, but the hook does not read it and keeps observing. |
Options
| Prop | Type | Description |
|---|---|---|
root | Element | Document | null | The element used as the viewport. The browser viewport when unset. |
rootMargin | string | Grows or shrinks the root box before computing intersections. |
threshold | number | 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) => void | Called with inView and the entry on every observer callback. |
Returns
| Prop | Type | Description |
|---|---|---|
inView | boolean | Whether the element last reported as intersecting at or above a threshold.Default: false |
ref | (element: HTMLElement | null) => void | Callback ref to attach to the observed element. Disconnects when the element detaches. |
Examples
Load more at the end of a list
const { ref } = useInView({
threshold: 0,
onChange: inView => {
if (inView) void fetchNext();
},
});
<div ref={ref} />