HooksuseLockBodyScroll

useLockBodyScroll()

The useLockBodyScroll() hook prevents the user from scrolling the main page body. This is essential when displaying modals, sidebars, or full-screen menus to prevent the background content from moving while the user interacts with the overlay.

Import

typescript
import { useLockBodyScroll } from 'the-react-hooks';

Usage

Click the button to open a modal and lock the main page scroll.

Component.tsx
import { useLockBodyScroll } from 'the-react-hooks';
import { useState } from 'react';

const Modal = ({ close }) => {
  useLockBodyScroll();

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <h2>Scroll is locked!</h2>
        <button onClick={close}>Close</button>
      </div>
    </div>
  );
};

export const Component = () => {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(true)}>Open Modal</button>
      {show && <Modal close={() => setShow(false)} />}
    </div>
  );
}

API

Arguments

This hook does not accept any arguments.

Returns

This hook returns void. It performs its side effect directly on the DOM.