Skip to main content

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, Dispatch<SetStateAction<boolean>>];
ParameterTypeDescription
initialStatebooleanThe initial state. Defaults to false.

Returns: a tuple of [state, toggle, setState].

Usage notes​

  • toggle is memoized with useCallback and 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.
  • Use the third element, setState, to set an explicit value, for example setOpen(false) when a menu item is picked. It is React's own setter, so it is stable too and also accepts an updater function.

Hook source​

View useToggleState source

use-toggle-state.ts
import type { Dispatch, SetStateAction } from "react";
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 initialState - The initial state of the toggle (default is `false`).
* @returns A tuple of the current state, a stable `toggle` function, and a stable `setState` for setting an explicit value (for example `setOpen(false)` to close).
*
* @example
* ```tsx
* const [isVisible, toggleVisibility] = useToggleState(false);
*
* return (
* <div>
* <button onClick={toggleVisibility}>
* {isVisible ? "Hide" : "Show"} Content
* </button>
* {isVisible && <p>This is some toggleable content!</p>}
* </div>
* );
* ```
*
* @example
* ```tsx
* const [isOpen, toggleOpen, setOpen] = useToggleState();
*
* return (
* <>
* <button onClick={toggleOpen}>Menu</button>
* {isOpen && <Menu onSelect={() => setOpen(false)} />}
* </>
* );
* ```
*
* 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, Dispatch<SetStateAction<boolean>>] => {
const [state, setState] = useState(initialState);

/**
* Toggles the current state between `true` and `false`.
*/
const toggle = useCallback(() => {
setState((prev) => !prev);
}, []);

return [state, toggle, setState];
};