HooksuseToggle

useToggle()

The useToggle() hook provides a simple way to manage boolean state. It returns the current state and a function to toggle it. The toggle function can also accept a specific boolean value to manually set the state.

Import

typescript
import { useToggle } from 'the-react-hooks';

Usage

Click the power button to toggle state. Use manual controls to set specific values.

System Off
Component.tsx
import { useToggle } from 'the-react-hooks';

export const Component = () => {
  const [isOn, toggle] = useToggle(false);

  return (
    <div>
      <p>State: {isOn ? 'ON' : 'OFF'}</p>
      
      <button onClick={() => toggle()}>
        Toggle
      </button>

      <button onClick={() => toggle(true)}>
        Turn On
      </button>

      <button onClick={() => toggle(false)}>
        Turn Off
      </button>
    </div>
  );
}

API

Arguments

  • initialValue boolean (Optional) The initial state value. Defaults to false.

Returns

Returns a tuple containing:
  • [0] value boolean The current state.
  • [1] toggle (value?: boolean) => void Function to update the state. Call without arguments to invert, or pass a boolean to set explicitly.