useToggle

Tags:

A React Hook for managing togglable states.

TIP

If you need to manage the rotation of multiple values (such as toggling between multiple languages or themes), it's recommended to use useCircularList.

Scenes

  • Toggle State Scenes: Quickly toggle between two states, such as theme switching (dark mode/light mode)
  • Form Item Selection: Managing states in options, such as gender selection (male/female)
  • Open/Closed or Enable/Disable: Toggle open/closed states, enable/disable, etc. (Direct use of useBoolean is recommended)
  • ...

Demo

Source
Mode:
light
Circular List:
A, B, C, D, E, F
Circular Value:
A

Usage

const [value, actions] = useToggle(['value 1', 'value 2']) actions.toggle() // Toggle the state actions.setLeft() // Set the state to left value actions.setRight() // Set the state to right value actions.setState('value 1') // Set the state to a specific value

Source

Click links below to view source on GitHub.

API

const [bool, actions] = useToggle(bool) const [value, actions] = useToggle([one, theOther])

Parameters

It accepts one or two parameters:

  • bool: A boolean value, the initial state, which will toggle between true and false.

  • one, theOther: The two values between which the state will toggle.

Returns

export interface UseToggleReturnsActions<O, T> { /** * Toggle the state. */ toggle(): void /** * Set the state to the left value. */ setLeft(): void /** * Set the state to the right value. */ setRight(): void /** * Set the state to a new value. */ setState: ReactSetState<O | T> } export type UseToggleReturns<O, T> = [O | T, UseToggleReturnsActions<O, T>]