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.

typescript
      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

typescript
      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/21 • Updated 18/03/23