h3/use's logo

h3/use

Command Palette

Search for a command to run...

useDisclosure

Manages boolean state for UI components like dialogs, modals, and popovers.

useDisclosure
This component uses the useDisclosure hook to manage the state of a dialog component.

Dialog is: Closed

Installation

Props

PropTypeDefaultDescription
initialStatebooleanfalseThe initial state of the disclosure
callbacksDisclosureCallbacks{}Callback functions for open and close events

Types

interface DisclosureCallbacks {
  onOpen?: () => void;
  onClose?: () => void;
}

Data

PropertyTypeDescription
isOpenbooleanThe current state of the disclosure
open() => voidFunction to open the disclosure
close() => voidFunction to close the disclosure
toggle() => voidFunction to toggle the disclosure state

Key Features & Details

State Management

  • The hook manages a boolean state that represents whether a component is open or closed
  • The state can be controlled through the returned functions: open, close, and toggle

Callbacks

  • onOpen: Called when the disclosure is opened
  • onClose: Called when the disclosure is closed
  • Callbacks are optional and can be used for side effects

Best Practices & Caveats

  • Use this hook for components that need to be shown/hidden
  • Perfect for dialogs, modals, popovers, and drawers
  • The hook is client-side only
  • For best performance, memoize the callbacks if they depend on other values

Examples

Basic Usage

const [isOpen, { open, close, toggle }] = useDisclosure();
 
return (
  <div>
    <button onClick={open}>Open</button>
    <button onClick={close}>Close</button>
    <button onClick={toggle}>Toggle</button>
    {isOpen && <div>Content</div>}
  </div>
);

With Initial State

const [isOpen, { open, close, toggle }] = useDisclosure(true);

With Callbacks

const [isOpen, { open, close, toggle }] = useDisclosure(false, {
  onOpen: () => console.log('Opened'),
  onClose: () => console.log('Closed'),
});

With Dialog Component

const [isOpen, { close, toggle }] = useDisclosure();
 
return (
  <Dialog open={isOpen} onOpenChange={toggle}>
    <DialogTrigger asChild>
      <Button>Open Dialog</Button>
    </DialogTrigger>
    <DialogContent>
      <DialogHeader>
        <DialogTitle>Example Dialog</DialogTitle>
        <DialogDescription>
          This is an example dialog controlled by useDisclosure.
        </DialogDescription>
      </DialogHeader>
      <DialogFooter>
        <Button variant="outline" onClick={close}>
          Close
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
);