useScrollLock
Lock and unlock scrolling on an element or the page.
useScrollLock
This component demonstrates locking and unlocking scroll on an element or the page.
Container scroll locked: No
Content line 1
Content line 2
Content line 3
Content line 4
Content line 5
Content line 6
Content line 7
Content line 8
Content line 9
Content line 10
Content line 11
Content line 12
Content line 13
Content line 14
Content line 15
Content line 16
Content line 17
Content line 18
Content line 19
Content line 20
Page scroll locked: No
Try scrolling this container or the page and use the buttons above.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
ref | RefObject<HTMLElement> <MutableRefObject<HTMLElement | null> | undefined | The ref of the element to lock scroll on. If not provided, locks the document body. |
Data
Prop | Type | Description |
---|---|---|
isLocked | boolean | Indicates if scrolling is locked. |
lock | () => void | Locks scrolling. |
unlock | () => void | Unlocks scrolling. |
toggle | () => void | Toggles the scroll lock. |
Key Features & Details
Target Behavior
- The hook accepts a ref to an element or defaults to the document body.
Cleanup
- Restores the original
overflow
style on unmount.
Performance & Safety
- Methods are memoized with
useCallback
. - Uses
useRef
to store the original overflow value.
Examples
Locking Element Scroll
import { useRef } from 'react';
import { useScrollLock } from '@/hooks/use-scroll-lock';
export function Example() {
const containerRef = useRef<HTMLDivElement>(null);
const { isLocked, lock, unlock, toggle } =
useScrollLock<HTMLDivElement>(containerRef);
return (
<div>
<button onClick={lock}>Lock</button>
<button onClick={unlock}>Unlock</button>
<button onClick={toggle}>{isLocked ? 'Unlock' : 'Lock'}</button>
<div ref={containerRef} style={{ height: '200px', overflow: 'auto' }}>
{/* content here */}
</div>
</div>
);
}
Locking Page Scroll
import { useScrollLock } from '@/hooks/use-scroll-lock';
export function PageExample() {
const { isLocked, lock, unlock } = useScrollLock();
return (
<div>
<button onClick={lock}>Lock Page</button>
<button onClick={unlock}>Unlock Page</button>
</div>
);
}