useBoolean()

A simple abstraction to play with a boolean, don't repeat yourself.

The Hook

1import { Dispatch, SetStateAction, useState } from 'react'
2
3interface ReturnType {
4 value: boolean
5 setValue: Dispatch<SetStateAction<boolean>>
6 setTrue: () => void
7 setFalse: () => void
8 toggle: () => void
9}
10
11function useBoolean(defaultValue?: boolean): ReturnType {
12 const [value, setValue] = useState(!!defaultValue)
13
14 const setTrue = () => setValue(true)
15 const setFalse = () => setValue(false)
16 const toggle = () => setValue(x => !x)
17
18 return { value, setValue, setTrue, setFalse, toggle }
19}
20
21export default useBoolean

Usage

1import React from 'react'
2
3import { useBoolean } from 'usehooks-ts'
4
5export default function Component() {
6 const { value, setValue, setTrue, setFalse, toggle } = useBoolean(false)
7
8 // Just an example to use "setValue"
9 const customToggle = () => setValue(x => !x)
10
11 return (
12 <>
13 <p>
14 Value is <code>{value.toString()}</code>
15 </p>
16 <button onClick={setTrue}>set true</button>
17 <button onClick={setFalse}>set false</button>
18 <button onClick={toggle}>toggle</button>
19 <button onClick={customToggle}>custom toggle</button>
20 </>
21 )
22}

Edit on CodeSandbox

See a way to make this page better?
Edit there »