useBooleanLoading saved progress…

useBoolean

Build a custom React hook that manages a single on/off flag. So much of an interface is just two states — a modal is open or closed, a panel is expanded or collapsed, a password is shown or hidden. useBoolean wraps useState and hands back the current value plus three named helpers — setTrue, setFalse, and toggle — so a component never has to spell out setOpen(true) or setOpen(!open) by hand again.

Signature

function useBoolean(initialValue?: boolean): {
  value: boolean;
  setTrue: () => void;
  setFalse: () => void;
  toggle: () => void;
};

initialValue defaults to false when omitted. setTrue and setFalse force the value to a fixed state; toggle flips whatever the value currently is.

Examples

function Disclosure() {
  const { value: open, setTrue, setFalse, toggle } = useBoolean(false);

  return (
    <div>
      <button onClick={toggle}>{open ? 'Hide' : 'Show'}</button>
      <button onClick={setTrue}>Open</button>
      <button onClick={setFalse}>Close</button>
      {open && <p>Now you see me.</p>}
    </div>
  );
}
// starts closed; toggle → open; toggle → closed; Open → open; Close → closed
// Toggling twice in one event must return to where it started.
// Starting from false, two toggles in the same batch land back on false.
toggle();
toggle();
// value === false

Notes

  • toggle flips relative to the current value. From false it goes true; from true it goes false. It does not always set a fixed state the way setTrue/setFalse do.
  • setTrue and setFalse are idempotent. Calling setTrue twice leaves the value true; there is no accumulation, unlike a counter.
  • Helpers must survive batched updates. React groups several setter calls in one event into one re-render, so toggle has to express its update in a way that stacks correctly rather than reading a stale snapshot.
  • You don't need to memoize the helpers for this version — returning fresh functions each render is fine. Stabilizing their identity is a separate exercise.
Loading editor…