Skip to main content

Overview

Cycles through an ordered list of values and exposes the current value with a function to move to the next value or to a specific target value. When options is not provided, it behaves like a boolean toggle between false and true.

Import

import { useToggle } from '@kuzenbo/hooks';

Signature

function useToggle<T = boolean>(
  options?: readonly T[]
): UseToggleReturnValue<T>;

Parameters

options
readonly T[]
Ordered values to cycle through. When not provided, defaults to [false, true]

Return Value

[value, toggle]
UseToggleReturnValue<T>
A tuple containing the current value and toggle function
value
T
Current value from the options list
toggle
(value?: SetStateAction<T>) => void
Function to cycle to the next value or set a specific value

Usage

Boolean Toggle

import { useToggle } from '@kuzenbo/hooks';

function ThemeToggle() {
  const [isDark, toggle] = useToggle();

  return (
    <button onClick={() => toggle()}>
      Current theme: {isDark ? 'Dark' : 'Light'}
    </button>
  );
}

Cycling Through Multiple Values

import { useToggle } from '@kuzenbo/hooks';

function ColorSelector() {
  const [color, toggleColor] = useToggle(['red', 'green', 'blue'] as const);

  return (
    <div>
      <div style={{ backgroundColor: color, width: 100, height: 100 }} />
      <button onClick={() => toggleColor()}>Next Color</button>
    </div>
  );
}

Set Specific Value

import { useToggle } from '@kuzenbo/hooks';

function ViewModeSelector() {
  const [view, setView] = useToggle(['grid', 'list', 'table'] as const);

  return (
    <div>
      <p>Current view: {view}</p>
      <button onClick={() => setView('grid')}>Grid</button>
      <button onClick={() => setView('list')}>List</button>
      <button onClick={() => setView('table')}>Table</button>
    </div>
  );
}

With Updater Function

import { useToggle } from '@kuzenbo/hooks';

function StatusToggle() {
  const [status, toggleStatus] = useToggle(['idle', 'loading', 'success', 'error'] as const);

  return (
    <div>
      <p>Status: {status}</p>
      <button onClick={() => toggleStatus((current) => 
        current === 'error' ? 'idle' : 'loading'
      )}>
        Update Status
      </button>
    </div>
  );
}

Type Definitions

type ToggleState<T> = [T, ...T[]];
type UseToggleAction<T> = (value?: SetStateAction<T>) => void;
export type UseToggleReturnValue<T> = [T, UseToggleAction<T>];

Build docs developers (and LLMs) love