Skip to Content
ohooks

useScrollSpy

Observes a list of page sections and returns the id of the currently active section in view.

Loading preview...

The useScrollSpy hook observes a list of section selectors or refs using IntersectionObserver and returns the id of the topmost visible section in the viewport—ideal for highlighting active links in a table of contents or sticky navigation bar.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useScrollSpy.json

Usage

Examples

Table of Contents Active Highlighting

Pass an array of section IDs or CSS selectors and compare activeId against each navigation link.

Custom Scroll Container and rootMargin

Provide a root container ref and custom rootMargin when spying on sections inside a scrollable panel instead of the window.

API Reference

UseScrollSpyOptions

Configuration options for intersection root, margins, and header offset.

Property
Specification
root?
uniondefault:s to the browser viewport
Scrollable root container
rootMargin?
stringdefault:'0px 0px -80% 0px'
IntersectionObserver root margin
threshold?
uniondefault:0
IntersectionObserver visibility threshold(s)
offset?
numberdefault:0
Top pixel offset subtracted when ranking visible sections