use-scroll-spy | Mantine

Track scroll position and detect which heading is currently in the viewport, can be used for table of contents

The use-scroll-spy hook tracks the scroll position and returns the index of the element that is currently in the viewport. It is useful for creating table of contents components (like in the mantine.dev sidebar on the right side) and similar features.

The use-scroll-spy hook accepts an object with options:

Example of using custom options to get headings with the data-heading attribute:

By default, use-scroll-spy attaches the scroll event listener to window . If your headings are located inside a scrollable container, pass that element to the scrollHost option. You can pass either a resolved HTMLElement or a ref object – the hook reads ref.current internally once the element is mounted:

The ref is resolved inside an effect after the component mounts, so the scroll host does not need to exist on the first render. Note that a plain ref object is not reactive – if you later point the ref at a different element, the hook keeps the listener on the original one. When the scroll host itself can change at runtime, pass the resolved element via state so that scrollHost changes identity and the hook re-runs with the new value.

By default, use-scroll-spy does not track changes in the DOM. If you want to update the headings data after the parent component has mounted, you can use the reinitialize function:

All types used in the definition are exported from @mantine/hooks package.

UseScrollSpyOptions and UseScrollSpyReturnValue types are exported from the @mantine/hooks package; you can import them in your application:

use-scroll-into-view

Recommended articles