usePreventBodyScrollui-interaction
usePreventBodyScroll
NewSSR SAFEPrevents background body scrolling with layout shift compensation and iOS Safari support.
$ pnpm dlx shadcn@latest add @byphongphan/use-prevent-body-scrollRequires
@byphongphan in components.jsonuse-prevent-body-scroll.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-prevent-body-scrollRequires
@byphongphan in components.jsonUsage
Features
- Layout Shift Prevention: Calculates the exact scrollbar width (
window.innerWidth - clientWidth) and applies compensatingpaddingRighttodocument.bodyso content does not jump when the scrollbar disappears. - iOS Safari Support: Applies
position: fixedclamped to-window.scrollYto prevent iOS WebKit momentum rubber-banding and elastic bounce scroll. - Reference Counting: Supports multiple nested modals, stacked drawers, or lightboxes. The body remains locked until the last open instance unmounts or sets
isOpen = false. - Instant Position Restoration: Disables smooth scroll behavior (
scrollBehavior: auto) during restore so users return to their exact scroll position without awkward animated scrolling. - SSR-Safe: Uses an isomorphic layout effect check to avoid hydration mismatch warnings in Next.js or other SSR environments.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
isOpen | boolean | true | Pass true to lock body scroll, or false to release. |
Returns
void - The hook manages lifecycle and body cleanup side-effects automatically.