Skip to main content

Overview

Manages boolean open/closed state with stable helper handlers. The open and close handlers are idempotent and invoke onOpen or onClose only when the state actually changes.

Import

import { useDisclosure } from '@kuzenbo/hooks';

Signature

function useDisclosure(
  initialState?: boolean,
  options?: UseDisclosureOptions
): UseDisclosureReturnValue;

Parameters

initialState
boolean
default:"false"
Initial disclosure state
options
UseDisclosureOptions
Optional lifecycle callbacks fired on state transitions
options.onOpen
() => void
Callback fired when the disclosure opens
options.onClose
() => void
Callback fired when the disclosure closes

Return Value

[opened, handlers]
UseDisclosureReturnValue
A tuple containing the current state and handler functions
opened
boolean
Current disclosure state
handlers
UseDisclosureHandlers
Object containing handler functions
handlers.open
() => void
Opens the disclosure (idempotent)
handlers.close
() => void
Closes the disclosure (idempotent)
handlers.toggle
() => void
Toggles the disclosure state
handlers.set
(value: boolean) => void
Sets the disclosure to a specific state

Usage

Basic Usage

import { useDisclosure } from '@kuzenbo/hooks';

function Modal() {
  const [opened, { open, close, toggle }] = useDisclosure(false);

  return (
    <>
      <button onClick={open}>Open Modal</button>
      <button onClick={close}>Close Modal</button>
      <button onClick={toggle}>Toggle Modal</button>
      
      {opened && (
        <div className="modal">
          <p>Modal content</p>
          <button onClick={close}>Close</button>
        </div>
      )}
    </>
  );
}

With Lifecycle Callbacks

import { useDisclosure } from '@kuzenbo/hooks';

function Drawer() {
  const [opened, { open, close }] = useDisclosure(false, {
    onOpen: () => console.log('Drawer opened'),
    onClose: () => console.log('Drawer closed'),
  });

  return (
    <>
      <button onClick={open}>Open Drawer</button>
      <div className={opened ? 'drawer-open' : 'drawer-closed'}>
        <button onClick={close}>Close</button>
      </div>
    </>
  );
}

Direct State Control

import { useDisclosure } from '@kuzenbo/hooks';

function Alert() {
  const [visible, { set }] = useDisclosure(true);

  return (
    <div>
      {visible && <div className="alert">Important message</div>}
      <button onClick={() => set(true)}>Show</button>
      <button onClick={() => set(false)}>Hide</button>
    </div>
  );
}

Type Definitions

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

export interface UseDisclosureHandlers {
  set: (value: boolean) => void;
  open: () => void;
  close: () => void;
  toggle: () => void;
}

export type UseDisclosureReturnValue = [boolean, UseDisclosureHandlers];

Build docs developers (and LLMs) love