typescriptbeginner
useLockBodyScroll Hook
Locks body scroll when active, commonly used with modals and overlays to prevent background scrolling.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useEffect } from 'react';
export function useLockBodyScroll(locked = true) {
useEffect(() => {
if (!locked) return;
const originalOverflow = document.body.style.overflow;
const originalPaddingRight = document.body.style.paddingRight;
const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.overflow = 'hidden';
document.body.style.paddingRight = `${scrollBarWidth}px`;
return () => {
document.body.style.overflow = originalOverflow;
document.body.style.paddingRight = originalPaddingRight;
};
}, [locked]);
}Use Cases
- Modal dialogs
- Full-screen overlays
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useIntersectionObserver Hook
Track element visibility with the Intersection Observer API for lazy loading and scroll animations.
Best for: Lazy loading images
#hooks#intersection-observer
typescriptintermediate
useScrollPosition Hook
Tracks window scroll position with throttling for performance-sensitive scroll effects.
Best for: Sticky headers
#hooks#scroll
typescriptadvanced
useFocusTrap Hook
Traps keyboard focus within a container for accessible modals and dialogs.
Best for: Accessible modals
#hooks#a11y
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch