useModal

A custom hook for managing modals.

Basic Usage

custom-modal.tsx
import {
Modal,
Button,
trapFocus,
useModal
} from '@cerberus/react'
function SomePage() {
const { modalRef, show, close } = useModal()
const handleKeyDown = trapFocus(modalRef)
return (
<div>
<Button onClick={show}>Show Modal</Button>
<Modal onKeyDown={handleKeyDown} ref={modalRef}>
This is a custom modal!
<Button onClick={close}>
Close
</Button>
</Modal>
</div>
)
}

Advanced Usage

When you need to dynamically load a Modal, you can use the useModal hook to manage the Modal's state.

This example demonstrates prefetching data before displaying the Modal. After the data is fetched (and cached), the Modal is displayed. Once the Modal is closed, the data is still available for future use.

API

interface UseModalReturnValue {
modalRef: RefObject<HTMLDialogElement>
show: () => void
close: () => void
isOpen: boolean
}
define function useModal(): UseModalReturnValue

Arguments

The useModal hook does not take any arguments.

Return Value

The useModal hook returns an object with the following properties:

NameDefaultDescription
modalRefThe ref that attaches to the Modal component.
showTriggers the Modal to open.
closeCloses the Modal.
isOpenfalseHelper value to know the state of the dialog.

On this page