use-toggle
Switch between two states
Import
Source
Docs
Package
Usage
Hook implements common state pattern – it switches state between two given values:
import { Button } from '@mantine/core';import { useToggle } from '@mantine/hooks';function Demo() {const [value, toggle] = useToggle('blue', ['blue', 'orange']);return (<Button color={value} onClick={() => toggle()}>{value}</Button>);}
API
Hook accepts two arguments:
initialValue
– initial stateoptions
– an array with 2 elements, must include initial value
Hook returns an array with state value and toggle function:
const [value, toggle] = useToggle('dark', ['light', 'dark']);toggle(); // -> value == 'light'toggle(); // -> value == 'dark'// You can force specific value, in this case state will be set to given valuetoggle('dark'); // -> value == 'dark'
use-boolean-toggle
use-boolean-toggle is a wrapper around use-toggle that works with boolean values:
import { useBooleanToggle, useToggle } from '@mantine/hooks';const [value, toggle] = useBooleanToggle(false);// same asconst [value, toggle] = useToggle(false, [true, false]);
TypeScript
Set type
By default TypeScript will guess your type, but in most cases it's better to set type manually:
const [value, toggle] = useToggle('dark', ['light', 'dark']); // value is stringconst [value, toggle] = useToggle<'dark' | 'light'>('dark', ['light', 'dark']); // value is 'dark' | 'light'
Definition
function useToggle<T>(initialValue: T,options: [T, T]): readonly [T, (value?: React.SetStateAction<T>) => void];
Built by Vitaly Rtishchev and these awesome people