# useScrollSpy (/docs/hooks/use-scroll-spy)





`useScrollSpy` reads the headings of a page and tracks the one being read as it scrolls. [`TableOfContents`](/docs/table-of-contents) is built on it. Reach for the hook when the table of contents is your own markup, or when something else should follow the reading position: a progress label, a header that shows the current section.

```tsx
import { useScrollSpy } from '@42-central/ui-react';

const spy = useScrollSpy({ container: '#subject', selector: 'h2, h3', offset: 64 });

spy.data.map((heading) => (
  <a
    key={heading.id}
    href={`#${heading.id}`}
    aria-current={heading.id === spy.active ? 'location' : undefined}
    onClick={(event) => {
      if (spy.scrollTo(heading.id)) event.preventDefault();
    }}
  >
    {heading.label}
  </a>
));
```

## Usage [#usage]

Scroll the box, or use the button, which calls `scrollTo`.

<Preview code="&#x22;const root = useRef(null);\nconst article = useRef(null);\nconst spy = useScrollSpy({ container: article, root, selector: 'h2, h3', offset: 16 });\nconst active = spy.data.find((heading) => heading.id === spy.active);\n\n<p>\n  Reading: {active ? active.label : 'nothing yet'}\n  <button onClick={() => spy.scrollTo('bonus-part')}>Jump to the bonus</button>\n</p>\n<div ref={root} className=\&#x22;h-80 overflow-auto\&#x22;>\n  <article ref={article}>…</article>\n</div>&#x22;">
  <ScrollSpyDemo />
</Preview>

## Which heading is active [#which-heading-is-active]

A heading becomes active once its top reaches `offset`, the height of whatever is stuck to the top of the scroller, and stays active until the next heading gets there. Before the first one reaches it, the first heading is active.

At the bottom of the page, the last sections are often too short for their headings to reach the line. So once the scroll can't go further, the last heading still in view wins, and the last entry of a table of contents can light up.

## Which sections are in view [#which-sections-are-in-view]

`visible` lists the `id` of every section in view, in order: from the one being read to the last heading above the bottom of the scroller. A section counts from its heading to the next one, so the section being read is always in the list, even when its heading has scrolled away. `TableOfContents`' `track` lights this range, and keeps `aria-current` for `active` alone.

## Scrolling to a heading [#scrolling-to-a-heading]

`scrollTo(id)` scrolls so the heading sits just below `offset`, and returns `false` when the heading isn't on the page. It scrolls by the distance between the heading and that line (`scrollBy`), never to an absolute `scrollTop`. So the same call works for the window and any nested scroller, and in either writing direction.

While its scroll runs, the target stays active, while `visible` follows the scroll. The headings it passes don't flash by, and it hands back to the reading position once the scroll has been still for a moment. It scrolls smoothly, or instantly when the reader prefers reduced motion; pass `{ behavior }` to choose.

`scrollTo` doesn't touch the URL. `TableOfContents` pushes the `#id` itself, after a click.

## Headings you already know [#headings-you-already-know]

Pass `data` to watch those headings instead of reading the page. They are returned as `data` straight away, so a server render already has them. A missing `label` or `depth` is filled from the heading after mount.

```tsx
const spy = useScrollSpy({
  data: [
    { id: 'introduction', label: 'Introduction', depth: 2 },
    { id: 'mandatory-part', label: 'Mandatory part', depth: 2 },
  ],
});
```

## When the content changes [#when-the-content-changes]

The headings are read after mount, and again when `container`, `selector` or `data` change. If the content under a fixed `container` changes later, for example after a fetch, call `reinitialize()`.

A heading without an `id` is skipped, since nothing could link to it, with a warning in development.

## API [#api]

<TypeTable
  type="{
  'options.container': {
    type: 'RefObject<Element | null> | string',
    description: 'Where to read the headings from: a ref, or a CSS selector. The whole document without it. Ignored with data.',
  },
  'options.selector': {
    type: 'string',
    default: '&#x22;h1, h2, h3, h4, h5, h6&#x22;',
    description: 'Which elements count as headings.',
  },
  'options.data': {
    type: '{ id: string; label?: string; depth?: number }[]',
    description: 'The headings to watch, in order, instead of reading the page. Returned before mount.',
  },
  'options.getDepth': {
    type: '(element: HTMLElement) => number',
    description: &#x22;A heading's level. By default, its tag's (3 for an h3), else its aria-level, else 1.&#x22;,
  },
  'options.getLabel': {
    type: '(element: HTMLElement) => string',
    description: &#x22;A heading's label. By default, its trimmed text.&#x22;,
  },
  'options.root': {
    type: 'RefObject<HTMLElement | null>',
    description: 'The element the headings scroll in. The window without it.',
  },
  'options.offset': {
    type: 'number',
    default: '0',
    description: 'The height in px of whatever is stuck to the top of root. A heading is active once it reaches this line, and scrollTo stops it just below.',
  },
}"
/>

Returns:

<TypeTable
  type="{
  active: {
    type: 'string | null',
    description: &#x22;The id of the heading being read. null on the server, before the first measure, and with no headings.&#x22;,
  },
  visible: {
    type: 'string[]',
    description: 'The ids of every section in view, in order, from the one being read to the last heading above the bottom of root. Empty until the first measure.',
  },
  data: {
    type: '{ id: string; label: string; depth: number; node: HTMLElement | null }[]',
    description: 'The headings, in document order. Empty until mount, unless data was passed.',
  },
  initialized: {
    type: 'boolean',
    description: 'true once the headings have been read from the page.',
  },
  reinitialize: {
    type: '() => void',
    description: 'Reads the headings again.',
  },
  scrollTo: {
    type: '(id: string, options?: { behavior?: ScrollBehavior }) => boolean',
    description: 'Scrolls root so the heading sits just below offset, keeping it active until the scroll settles. false when the heading is not on the page.',
  },
}"
/>

`active` is `null` on the server and on the first client render, then the real heading right after mount, like the other hooks that read the page. See [SSR-safe first render](/docs/hooks#ssr-safe-first-render).
