useToggle

useToggle

This hook allows you to manage toggle state in a functional component. It returns an array containing the current state of the toggle, a callback function to toggle the state and a callback function to set the state directly.

Props

initialValue: The initial state of the toggle.

Returns

  • value: The current state of the toggle (true or false).
  • toggle: A callback function to toggle the state of the toggle. If called with a value, the toggle will be set to that value. If called without a value, the toggle will be flipped (true to false, or false to true).
  • setValue: A callback function to set the state of the toggle directly.

The Hook

useToggle.ts
import { useState, useCallback, Dispatch, SetStateAction } from 'react'
 
export const useToggle = (
  initialValue: boolean
): [boolean, () => void, Dispatch<SetStateAction<boolean>>] => {
  const [value, setValue] = useState<boolean>(initialValue)
 
  const toggle = useCallback((value?: boolean) => {
    setValue((prevState) => value ?? !prevState)
  }, [])
 
  return [value, toggle, setValue]
}

Usage

OnClickToggle.tsx
import React from 'react'
import { useToggle } from './useToggle'
 
export const UseToggleDemo = () => {
  const [value, toggle, setValue] = useToggle(false)
 
  return (
    <div>
      <p>Current Value: {value?.toString()}</p>
      <button onClick={() => toggle()} type='button'>
        Toggle
      </button>
      <button onClick={() => setValue(true)}>Set Value</button>
    </div>
  )
}