Skip to main content

useToggle

useToggle is a custom React hook that manages a boolean state and provides a stable function to toggle it or force it to a specific value.

Usage

import { useToggle } from "hookify-react";

export default function UseToggleExample() {
const [isToggled, toggle] = useToggle(false);

return (
<div>
<button onClick={() => toggle()}>Toggle</button>
<button onClick={() => toggle(true)}>On</button>
<button onClick={() => toggle(false)}>Off</button>
<p>Toggle is: {isToggled ? "On" : "Off"}</p>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
initialValuebooleanfalseThe initial boolean state. Optional; defaults to false.

Return Value

useToggle returns a tuple [state, toggle].

PropertyTypeDescription
statebooleanThe current boolean state.
toggle(value?: boolean) => voidFlips the state when called with no argument, or sets it explicitly when passed true/false.

Behavior

  • initialValue is optional and defaults to false.
  • Calling toggle() with no argument flips the current value.
  • Calling toggle(true) or toggle(false) forces the state to that value.
  • The toggle function has a stable identity across renders.