DOMIntermediateSSR-safehooks/dom/useLockBodyScroll.ts

useLockBodyScroll

Prevent page scroll (modals).

Import

TypeScript
import { useLockBodyScroll } from '@/hooks';

API

Signature

useLockBodyScroll(locked?)

When to use

Use useLockBodyScroll instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Measurements are 0 / empty until the element is mounted.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useLockBodyScroll
Editor
function ModalBody({ open }: { open: boolean }) {
  useLockBodyScroll(open);
  return open ? <div role="dialog">Modal</div> : null;
}
Preview

Implementation source

Full library source for useLockBodyScroll — copy into your project when you are not installing a package yet.

hooks/dom/useLockBodyScroll.ts
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
import { isBrowser } from '../utility/isBrowser';

/** Locks `document.body` scroll while `locked` is true. */
export function useLockBodyScroll(locked = true): void {
  useIsomorphicLayoutEffect(() => {
    if (!isBrowser() || !locked) return;
    const original = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = original;
    };
  }, [locked]);
}

Copy-paste example

useLockBodyScroll.example.tsx
'use client';

import { useLockBodyScroll } from '@/hooks';

export function ModalBody({ open }: { open: boolean }) {
  useLockBodyScroll(open);
  return open ? <div role="dialog">Modal</div> : null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Attach the ref before measuring. ResizeObserver requires a mounted element.
  • Source of truth: open hooks/dom/useLockBodyScroll.ts for implementation details