useBoolean (React)

Toggle a piece of boolean state, but unlike with straight useState you can pass the setState function no arguments to toggle the boolean.

typescriptjavascript
import type { Dispatch } from 'react'
import { useReducer } from 'react'
 
export const useBoolean = (
  initialValue = false
): [boolean, (nextValue?: boolean) => void] => {
  return useReducer((currentValue: boolean, nextValue?: boolean) => {
    return typeof nextValue !== 'undefined' ? nextValue : !currentValue
  }, initialValue)
}
import { useReducer } from 'react'
 
export const useBoolean = (initialValue = false) => {
  return useReducer((currentValue, nextValue) => {
    return typeof nextValue !== 'undefined' ? nextValue : !currentValue
  }, initialValue)
}

Usage

typescriptjavascript
const Example = () => {
  const [on, toggle] = useBoolean()
 
  return (
    <>
      <h1>Value {on ? 'true' : 'false'}</h1>
      <button onClick={() => toggle(true)}>On</button>
      <button onClick={() => toggle(false)}>Off</button>
      <button onClick={() => toggle()}>Toggle</button>
    </>
  )
}
const Example = () => {
  const [on, toggle] = useBoolean()
 
  return (
    <>
      <h1>Value {on ? 'true' : 'false'}</h1>
      <button onClick={() => toggle(true)}>On</button>
      <button onClick={() => toggle(false)}>Off</button>
      <button onClick={() => toggle()}>Toggle</button>
    </>
  )
}
Created 02/05/21Updated 18/03/23
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here