useDisclosure
Manages boolean state for UI components like dialogs, modals, and popovers.
Installation
Props
Prop | Type | Default | Description |
---|
initialState | boolean | false | The initial state of the disclosure |
callbacks | DisclosureCallbacks | {} | Callback functions for open and close events |
Types
interface DisclosureCallbacks {
onOpen?: () => void;
onClose?: () => void;
}
Data
Property | Type | Description |
---|
isOpen | boolean | The current state of the disclosure |
open | () => void | Function to open the disclosure |
close | () => void | Function to close the disclosure |
toggle | () => void | Function 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>
);