Skip to main content

useBoolean

React state hook that manages a boolean value

Usage

Live Editor
function Demo() {
  const { value, setValue, setTrue, setFalse, toggle } = useBoolean(false);

  return (
    <div>
      <p>Current value: <strong>{value ? 'True' : 'False'}</strong></p>
      <div style={{ marginBottom: 16 }}>
        <button
          type="button"
          onClick={() => setValue(true)}
          style={{ marginRight: 8 }}
          disabled={value}
        >
          Set True
        </button>
        <button
          type="button"
          onClick={() => setValue(false)}
          style={{ marginRight: 8 }}
          disabled={!value}
        >
          Set False
        </button>
        <button
          type="button"
          onClick={setTrue}
          style={{ marginRight: 8 }}
          disabled={value}
        >
          setTrue()
        </button>
        <button
          type="button"
          onClick={setFalse}
          style={{ marginRight: 8 }}
          disabled={!value}
        >
          setFalse()
        </button>
        <button
          type="button"
          onClick={toggle}
          style={{ marginRight: 8 }}
        >
          Toggle
        </button>
      </div>
      <div>
        <p>Status: {value ? '✅ Enabled' : '❌ Disabled'}</p>
      </div>
    </div>
  );
};
Result

Current value: False

Status: ❌ Disabled

API

useBoolean

Returns

{ readonly value: boolean; readonly setValue: (value: boolean) => void; readonly setTrue: () => void; readonly setFalse: () => void; readonly toggle: () => void; }: An object with the following properties:

  • value: The current boolean value.
  • setValue: A function to set the boolean value directly.
  • setTrue: A function to set the value to true.
  • setFalse: A function to set the value to false.
  • toggle: A function to toggle the boolean value.

Arguments

ArgumentDescriptionTypeDefaultValue
initialValueThe initial boolean value. Defaults to false.boolean | undefined-
ads via Carbon