raddix

useToggle

Toggles state between given values.

Installation

Install the custom hook from your command line.

npm i @raddix/use-toggle

Usage

To toggle the state between given values ​​add an array to the useToggle hook.

The first element of the array will be used by default as the initial value, you can override this by adding the desired initial value as the second parameter.

import { useToggle } from '@raddix/use-toggle';
export default function App() {
const [color, toggle, setColor] = useToggle(['blue', 'orange', 'cyan']);
return (
<div>
<button onClick={toggle}>{color}</button>
<button onClick={() => setColor('blue')}>Set color blue</button>
<button onClick={() => setColor('cyan')}>Set color cyan</button>
</div>
)
}

API

Parameters

NameDescriptionRequiredDefault ValueType
valuesAn array of valuesYes-Array<T>
initValueinitial valueNovalues[0]T

Result

The useToggle hook returns an array with the following elements:

IndexDescriptionType
[0]The current value of the state.T
[1]A function to toggle the state.function
[2]A function to change the state.function