use-toggle

Switch between two states
Import

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 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'

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 as
const [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 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];
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback