v6.0.35

use-toggle

Switch between given values
Import

Usage

use-toggle hook implements a common state pattern – it switches state between given values:

import { Button } from '@asuikit/core';
import { useToggle } from '@asuikit/hooks';
function Demo() {
const [value, toggle] = useToggle(['blue', 'orange', 'cyan', 'teal']);
return (
<Button color={value} onClick={() => toggle()}>
{value}
</Button>
);
}

API

Hook accepts an array as single argument, the first option will be used as the default value.

Hook returns an array with state value and toggle function:

const [value, toggle] = useToggle(['light', 'dark'] as const);
toggle(); // -> value == 'light'
toggle(); // -> value == 'dark'
// You can force specific value, in this case state will be set to given value
toggle('dark'); // -> value == 'dark'

If you do not provide an array with options, then use-toggle will use boolean values with false as default:

const [value, toggle] = useToggle();
// -> value === false
toggle(); // -> value === true

TypeScript

Set type

By default, TypeScript will guess your type, but in most cases it's better to use const assertion to prevent type widening:

const [value, toggle] = useToggle(['light', 'dark']); // value is string
const [value, toggle] = useToggle(['light', 'dark'] as const); // value is 'dark' | 'light'
const [value, toggle] = useToggle<'dark' | 'light'>(['light', 'dark']); // same as above

Definition

function useToggle<T = boolean>(
options?: readonly T[]
): readonly [T, (value?: React.SetStateAction<T>) => void];