# 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

- Don't: Rely on `triggerOnce`. The type accepts it, but the hook does not read it and keeps observing.

## Options

| Prop | Type | Default | 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[]` | `0` | Ratio or ratios of visibility the element must reach to count as in view. Read when the ref attaches. |
| `onChange` | `(inView: boolean, entry: IntersectionObserverEntry) => void` |  | Called with `inView` and the entry on every observer callback. |

## Returns

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `inView` | `boolean` | `false` | Whether the element last reported as intersecting at or above a threshold. |
| `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

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

<div ref={ref} />
```
