use-toggle

Switch between two states
Import

Usage

use-toggle implements a 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 state
  • options – 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 value
toggle('dark'); // -> value == 'dark'

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 string
const [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];