useToggleState
Manages a boolean state with a single toggle function. A minimal, ergonomic
replacement for useState(false) plus a manual toggler.
When to use it
- Showing/hiding UI elements (dropdowns, modals, password visibility).
- Switching between two visual states (active/inactive, on/off).
- Any binary state that flips back and forth on user interaction.
Demo
Loading demo…
Signature
function useToggleState(initialState?: boolean): [boolean, () => void];
| Parameter | Type | Description |
|---|---|---|
initialState | boolean | The initial state. Defaults to false. |
Returns: a tuple of [state, toggle].
Usage notes
toggleis memoized withuseCallbackand never changes identity across renders, so it's safe to pass down to child components or effect deps.- Call
toggle()with no arguments — it always flips the current state.
Hook source
View useToggleState source
useToggleState sourceuse-toggle-state.ts
import { useCallback, useState } from "react";
/**
* A custom React hook for toggling a boolean state.
*
* This hook is useful for managing binary states, such as showing/hiding elements, toggling themes, or activating/deactivating features.
*
* @param {boolean} [initialState=false] - The initial state of the toggle (default is `false`).
* @returns {[boolean, () => void]} - An array containing the current state and a function to toggle it.
*
* @example
* ```typescript
* const [isVisible, toggleVisibility] = useToggleState(false);
*
* return (
* <div>
* <button onClick={toggleVisibility}>
* {isVisible ? "Hide" : "Show"} Content
* </button>
* {isVisible && <p>This is some toggleable content!</p>}
* </div>
* );
* ```
*
* For a live, editable example, see the [useToggleState docs page](https://altalyst-solutions.github.io/hookify/hooks/use-toggle-state).
*/
export const useToggleState = (
initialState: boolean = false
): [boolean, () => void] => {
const [state, setState] = useState(initialState);
/**
* Toggles the current state between `true` and `false`.
*/
const toggle = useCallback(() => {
setState((prev) => !prev);
}, []);
return [state, toggle] as const;
};