Skip to main content

useToggle()

The useToggle() hook can toggle between a set of two possible values and automatically update the state with the new value, if you want to toggle a boolean's state, see useBoolToggle() below.

Import

import { useToggle } from 'react-haiku';

Usage

Theme: dark

General

import { useToggle } from 'react-haiku';

export const Component = () => {
const [theme, toggleTheme] = useToggle('dark', ['dark', 'light']);

return (
<>
<b>{`Theme: ${theme}`}</b>
<button onClick={() => toggleTheme()}>Toggle!</button>
</>
);
}

Boolean

import { useBoolToggle } from 'react-haiku';

export const Component = () => {
const [isTrue, toggleTrue] = useBoolToggle(true) // default initial value is false

return (
<>
<b>{`State: ${isTrue}`}</b>
<button onClick={() => toggleTrue()}>Toggle!</button>
</>
);
}

API

This hook accepts the following arguments:

  • initialValue - the initial preferred value for the toggle state
  • options - must be an array with strictly 2 elements and must also contain the value set for initialValue