use-smooth-scroll-restore
v1.0.1
Published
The ultimate React hook for seamless scroll position restoration across routes, tabs, and sessions. Zero-config, lightweight, and flicker-free.
Maintainers
Readme
🌊 use-smooth-scroll-restore
The ultimate React hook for seamless scroll position restoration. Engineered to fix the "jump-to-top" bug across routes, tabs, and browser back/forward buttons.
✨ Why Every App Needs This
Most SPAs (Single Page Apps) lose the user's scroll position when they navigate away or hit the back button. use-smooth-scroll-restore provides a privacy-first, flicker-free solution.
- ✅ Browser Back/Forward: Lands exactly where the user left off.
- ✅ Refresh Persistence: Remembers position even after a hard refresh.
- ✅ Mobile Safari Fix: Optimized for iOS scroll-jumping edge cases.
- ✅ Performance First: Throttled event listeners +
requestAnimationFrame. - ✅ Zero Dependencies: Tiny footprint (< 1kB gzipped).
📦 Installation
npm install use-smooth-scroll-restore🚀 Usage
Simply call the hook in your top-level page components or a layout wrapper.
import { useSmoothScrollRestore } from 'use-smooth-scroll-restore';
function BlogPage() {
// Remembers scroll position automatically
useSmoothScrollRestore();
return (
<main>
<h1>Long Content...</h1>
</main>
);
}⚙️ Advanced Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| throttle | number | 100 | Delay (ms) between scroll tracking updates. |
| key | string | 'scroll-restore' | Custom prefix for sessionStorage keys. |
| isEnabled | boolean | true | Programmatically enable/disable tracking. |
🛡️ Privacy
This hook uses sessionStorage, meaning all scroll data is wiped when the tab is closed. No cookies, no local storage, and zero tracking.
🧠 How it Works
By leveraging useLayoutEffect and requestAnimationFrame, we ensure the scroll restoration happens before the browser paints. This eliminates the "flash of top-page" content, making navigation feel native and instantaneous.
