typescriptbeginner

useLockBodyScroll Hook

Locks body scroll when active, commonly used with modals and overlays to prevent background scrolling.

typescript
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.