useModal
Disclosure + scroll lock + Escape + trap.
Import
TypeScript
import { useModal } from '@/hooks';API
Signature
useModal(options?) → disclosure + DOM helpers
When to use
Use useModal instead of re-implementing the same pattern in multiple components.
SSR / Next.js
DOM extras (scroll lock, focus trap) run only in effects.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useModalEditor
function Confirm() { const ref = useRef<HTMLDivElement>(null); const modal = useModal({ containerRef: ref }); return ( <> <button onClick={modal.open}>Open</button> {modal.isOpen && ( <div ref={ref} role="dialog"> <p>Sure?</p> <button onClick={modal.close}>Close</button> </div> )} </> ); }
Preview
Implementation source
Full library source for useModal — copy into your project when you are not installing a package yet.
hooks/ui/useModal.ts
import { useDisclosure, type UseDisclosureOptions } from './useDisclosure';
import { useLockBodyScroll } from '../dom/useLockBodyScroll';
import { useEscapeKey } from '../events/useEscapeKey';
import { useFocusTrap } from '../dom/useFocusTrap';
import type { RefObject } from 'react';
export interface UseModalOptions extends UseDisclosureOptions {
/** Lock body scroll while open. @default true */
lockScroll?: boolean;
/** Close on Escape. @default true */
closeOnEscape?: boolean;
/** Optional container for focus trap. */
containerRef?: RefObject<HTMLElement | null>;
/** Enable focus trap when containerRef is provided. @default true */
trapFocus?: boolean;
}
/** Modal helpers: disclosure + scroll lock + escape + optional focus trap. */
export function useModal(options: UseModalOptions = {}) {
const {
lockScroll = true,
closeOnEscape = true,
containerRef,
trapFocus = true,
...disclosureOptions
} = options;
const disclosure = useDisclosure(disclosureOptions);
useLockBodyScroll(lockScroll && disclosure.isOpen);
useEscapeKey(
() => {
if (disclosure.isOpen) disclosure.close();
},
{ enabled: closeOnEscape && disclosure.isOpen },
);
if (containerRef) {
// hooks cannot be conditional — call always, gate with active
}
useFocusTrap(
containerRef ?? { current: null },
Boolean(containerRef) && trapFocus && disclosure.isOpen,
);
return disclosure;
}
Copy-paste example
useModal.example.tsx
'use client';
import { useRef } from 'react';
import { useModal } from '@/hooks';
export function Confirm() {
const ref = useRef<HTMLDivElement>(null);
const modal = useModal({ containerRef: ref });
return (
<>
<button onClick={modal.open}>Open</button>
{modal.isOpen && (
<div ref={ref} role="dialog">
<p>Sure?</p>
<button onClick={modal.close}>Close</button>
</div>
)}
</>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: These are headless — you own the markup and styles.
- Source of truth: open
hooks/ui/useModal.tsfor implementation details