npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-use-active-scroll

v0.0.1

Published

Accurate TOC/sidebar links without compromises for React.

Readme

React Use Active Scroll

npm version npm downloads bundle JSDocs License

Live Demo: https://condorheroblog.github.io/react-use-active-scroll/

A React hook that tracks the currently active section while scrolling. Ideal for TOC and sidebar link highlighting.

Why?

The Intersection Observer API makes it hard, if not impossible, to:

  • Highlight a clicked link even if it will never intersect
  • Always highlight the first/last link once the top/bottom of the page is reached
  • Get consistent results regardless of scroll speed
  • Immediately highlight links on click or hash navigation when smooth scrolling is enabled

React Use Active Scroll implements a custom scroll observer that adapts to any scroll behavior — CSS scroll-behavior, scrollIntoView or JS animation libraries — and always returns the "correct" active target.

What it doesn't do

  • Scroll to targets
  • Mutate the DOM or inject styles (the opt-in debug overlay is the single exception, and only when you render its node)
  • Require or configure hash navigation

Installation

npm i react-use-active-scroll
# pnpm add react-use-active-scroll
# yarn add react-use-active-scroll

Quick Start

import { useActiveScroll } from "react-use-active-scroll";

const sections = [
	{ id: "introduction", title: "Introduction" },
	{ id: "quick-start", title: "Quick Start" },
	{ id: "api", title: "API" },
];

export function App() {
	const { activeId, setActive } = useActiveScroll(sections.map(s => s.id));

	return (
		<>
			<main>
				{sections.map(s => (
					<section key={s.id}>
						<h2 id={s.id}>{s.title}</h2>
						<p>{/* ... */}</p>
					</section>
				))}
			</main>

			<nav>
				{sections.map(s => (
					<a
						key={s.id}
						href={`#${s.id}`}
						className={activeId === s.id ? "active" : ""}
						onClick={() => setActive(s.id)}
					>
						{s.title}
					</a>
				))}
			</nav>
		</>
	);
}

Add smooth scrolling somewhere in your global CSS:

html {
	scroll-behavior: smooth; /* or 'auto' */
}

[!TIP] Always call setActive(id) in your click handler: it makes highlighting immediate and consistent regardless of scroll speed or easing.

Targets

Targets accept an array of IDs, an array of elements, or a ref holding either:

const byId = ["introduction", "quick-start"];
const byEl = [headingEl1, headingEl2];
const byRef = targetsRef; // useful when targets mount later

Options

export function Sidebar() {
	const { activeId } = useActiveScroll(targets, {
		direction: "vertical", // scroll axis: "vertical" | "horizontal"
		root: null, // scrolling element, window root by default
		overlay: 0, // fixed overlay size along the scroll axis, in px
		mediaQuery: "", // CSS media query gate, e.g. "(min-width: 768px)"
		hash: "off", // sync URL hash: "off" | "replace" | "push"
		edges: { first: true, last: true }, // edge activation strategy
		offset: 0, // boundary offset, number or { toStart, toEnd }
		debug: false, // render trigger-line devtools: false | true | { label, className }
	});

	return <nav>{/* ... */}</nav>;
}

| Property | Type | Default | Description | | --------- | -------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | direction | 'vertical' \| 'horizontal' | 'vertical' | Scroll axis to track. 'horizontal' watches scrollLeft instead of scrollTop (RTL is not supported yet). | | edges | Edges | { first: true, last: true } | Activation strategy for the first/last target. true always activates the edge target once reached the start/end even if not intersecting. A number allows "no active target": the first target activates early when within that distance of the trigger line; the last target deactivates after its end passes the line by that distance. | | hash | 'off' \| 'replace' \| 'push' | 'off' | Sync URL hash while scrolling. replace updates the current history entry, push creates a new one. The first target is skipped if edges.first is true. | | offset | number \| Offset | { toStart: 0, toEnd: 0 } | Boundary offset in px per scroll direction (toStart when scrolling towards the start, toEnd towards the end). A single number applies to both. Tweak to "anticipate" or "delay" target detection. | | root | HTMLElement \| null | RefObject<HTMLElement \| null> | null | Scrolling element. Set it only if your content is not scrolled by the window. If null, defaults to the document root. | | overlay | number | 0 | Size in px of any CSS fixed content overlapping the start of your scrolling area along the scroll axis — a fixed header (vertical) or a fixed side panel (horizontal). Must be paired with scroll-margin-top / scroll-margin-left on your targets. | | mediaQuery | string | '' | A CSS media query, e.g. '(min-width: 768px)'; listeners are enabled only while it matches the viewport. Useful when hiding the sidebar with display: none on small screens. An invalid query is ignored (with a console warning) and listeners stay always enabled; the same applies when it is omitted. | | debug | boolean \| DebugOptions | false | Renders a trigger-line debug overlay. true enables it; an object accepts label (show text labels, default true) and className (extra class on the overlay wrapper). Render the returned devtools node yourself. Colors are themed via CSS variables. |

Return Value

| Name | Type | Description | | ----------- | -------------------------------------------- | --------------------------------------------------------------------------- | | setActive | (target: string \| HTMLElement) => void | Include it in your click handler to ensure adaptive behavior. | | isActive | (target: string \| HTMLElement) => boolean | Whether the given ID or element is currently active. | | activeElement | HTMLElement \| null | The active target element. | | activeId | string | The active target ID, an empty string when inactive. | | activeIndex | number | Index of the active target in offset order, -1 when inactive. | | devtools | ReactNode | Trigger-line debug overlay node, null unless debug is enabled. Render it anywhere for window scrolling, or as a sibling of the scroll container inside a position: relative wrapper for container scrolling. |

Recipes

Scrolling container

export function Layout() {
	const containerRef = useRef<HTMLDivElement>(null);

	const { activeId } = useActiveScroll(ids, { root: containerRef });

	return (
		<div ref={containerRef} className="scroll-container">
			{/* sections */}
		</div>
	);
}
.scroll-container {
	overflow-y: auto;
	scroll-behavior: smooth;
}

Fixed header

If a fixed header overlaps the top of the scrolling area, set its height via overlay and pair it with scroll-margin-top so clicked targets don't hide underneath:

export function Sidebar() {
	const { activeId } = useActiveScroll(ids, { overlay: 64 });

	return <nav>{/* ... */}</nav>;
}
h2 {
	scroll-margin-top: 64px;
}

Horizontal scrolling

Set direction: "horizontal" to track a horizontally scrolling container. Fixed overlays on the left use the same overlay option (their width), paired with scroll-margin-left:

export function Sidebar() {
	const { activeId } = useActiveScroll(ids, {
		root: containerRef,
		direction: "horizontal",
	});

	return <nav>{/* ... */}</nav>;
}
.scroll-container {
	display: flex;
	overflow-x: auto;
	scroll-behavior: smooth;
}

Fine-tuning activation

export function Sidebar() {
	// Allow "no active target": the first activates 120px before crossing the
	// trigger line, the last deactivates 160px after its bottom passes it
	const { activeId } = useActiveScroll(ids, {
		edges: { first: 120, last: 160 },
		offset: { toStart: 50, toEnd: 100 }, // per-direction boundary offset
		hash: "replace", // keep the URL hash in sync while scrolling
	});

	return <nav>{/* ... */}</nav>;
}

Debug overlay (trigger lines)

Set debug: true and render the returned devtools node to visualize the exact trigger lines used by the activation algorithm — handy while tuning overlay, offset, and edges:

export function Sidebar() {
	const { activeId, devtools } = useActiveScroll(ids, { debug: true });

	return (
		<>
			{/* ... */}
			{devtools}
		</>
	);
}
  • Window scrolling: devtools is position: fixed, so you can render it anywhere in the tree.
  • Container scrolling: render it as a sibling of the scroll container, inside a position: relative wrapper:
<div style={{ position: "relative" }}>
	<div ref={containerRef} style={{ overflow: "auto" }}>
		{/* sections */}
	</div>
	{devtools}
</div>;

Reading the lines. Dashed lines are the directional trigger lines: ↓ / → scroll toward the end (offset.toEnd), ↑ / ← scroll toward the start (offset.toStart). Dotted lines are the first/last edge-offset lines and only appear when edges.first / edges.last are numbers (or false). Coincident lines are merged into one label, and every label shows its position in px from the root border-box. A line beyond the start edge (negative position) is shown as a pinned off-screen marker.

Pass an object to tweak the overlay — debug: { label: false } hides the labels, debug: { className: "my-debug" } adds a class to the overlay wrapper. Colors and stacking are themed through CSS custom properties (inline styles with fallbacks — no stylesheet is injected):

| CSS variable | Default | Used for | | ------------------- | --------- | --------------------------------- | | --uas-debug-line | #22d3ee | Directional trigger lines/labels | | --uas-debug-edge | #f59e0b | First/last edge lines/labels | | --uas-debug-bg | #ffffff | Label background | | --uas-debug-z-index | 9999 | Overlay stacking order |

Server-side rendering

The hook only activates after hydration. Render the first link as active on the server to avoid a flash:

export function Sidebar({ ids }: { ids: string[] }) {
	const [mounted, setMounted] = useState(false);
	useEffect(() => setMounted(true), []);

	const { activeId } = useActiveScroll(ids);
	const currentId = mounted ? activeId : ids[0];

	return <nav>{/* render links, highlight currentId */}</nav>;
}

License

MIT License © 2026-Present Condor Hero