Rehooks
Content

useToggle

A hook that provides a boolean state and a function to toggle it.

useToggle

Usage

Component.tsx
import { useToggle } from "~/hooks/useToggle";
 
function Component() {
  const [isOn, toggle, setToggle] = useToggle(false);
 
  return (
    <div>
      <p>Current state: {isOn ? "On" : "Off"}</p>
      <button onClick={toggle}>Toggle</button>
      <button onClick={() => setToggle(true)}>Turn On</button>
      <button onClick={() => setToggle(false)}>Turn Off</button>
    </div>
  );
}

API

useToggle

function useToggle(
  defaultValue?: boolean,
): [boolean, () => void, Dispatch<SetStateAction<boolean>>];

Returns a stateful value and two functions to update it.

Parameters

NameTypeDescription
defaultValuebooleanThe initial value of the state. Default is false.

Returns

NameTypeDescription
isOnbooleanThe current value of the state.
toggle() => voidA function to toggle the state.
setToggleDispatchA function to set the state to a new value.

On this page