Skip to content

useToggle

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useToggle

Toggle between two generic values (e.g., "light" and "dark", or 0 and 1). If no secondary value is provided, it elegantly falls back to standard boolean toggling behavior.

Usage Examples

Basic

A simple boolean toggle, acting much like useBoolean but with a simpler destructured return array.

import { useToggle } from "react-hook-lab";

function BasicToggle() {
  const { value: isPlaying, toggle } = useToggle(false);

  return (
    <div>
      <p>Status: {isPlaying ? "Playing" : "Paused"}</p>
      <button onClick={toggle}>
        {isPlaying ? "Pause" : "Play"}
      </button>
    </div>
  );
}

Common

Toggling between two distinct string values (like themes).

import { useToggle } from "react-hook-lab";

function ThemeSwitcher() {
  // Toggles between "light" and "dark"
  const { value: theme, toggle: toggleTheme } = useToggle("light", "dark");
  
  return (
    <div className={`app-${theme}`}>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Switch Theme</button>
    </div>
  );
}

Advanced

Toggling between custom objects or complex generic types.

import { useToggle } from "react-hook-lab";

type UserRole = { role: string; accessLevel: number };

const GUEST: UserRole = { role: "Guest", accessLevel: 1 };
const ADMIN: UserRole = { role: "Admin", accessLevel: 10 };

function RoleTester() {
  const { value: userRole, toggle: switchRole } = useToggle<UserRole>(GUEST, ADMIN);
  
  return (
    <div>
      <p>Current Role: {userRole.role} (Level {userRole.accessLevel})</p>
      <button onClick={switchRole}>Swap Identity</button>
    </div>
  );
}

API Reference

Parameters

  • defaultValue
    • Type: T
    • Description: The primary, initial value.
  • reverseValue (Optional)
    • Type: T
    • Description: The secondary value to toggle to. If omitted, the hook assumes boolean behavior and toggles !value.

Return Object

Returns an object containing:

  • value (T): The current state.
  • setValue (Dispatch<SetStateAction<T>>): Standard React state setter function to force a specific value.
  • toggle (() => void): A stable, memoized function that switches the state between defaultValue and reverseValue.

Core Working

Under the hood, useToggle manages a generic generic type T via React's useState. When the toggle function is called:

  • If a reverseValue was provided, it explicitly checks if the current state strictly equals (===) the defaultValue. If it does, it sets the state to reverseValue, otherwise it reverts it back to defaultValue.
  • If reverseValue is undefined, it simply coerces the previous state to a boolean and negates it via !prev as T.

The toggle method is wrapped in useCallback with dependencies on defaultValue and reverseValue, meaning its reference will remain perfectly stable as long as the provided values don't change identity across renders.

Clone this wiki locally