useToggle

React hook to toggle a boolean value.

import { useState } from 'react'

export const useToggle = (initialValue: boolean) => {
  const [current, setCurrent] = useState(initialValue)

  const handleToggle = () => setCurrent((prev) => !prev)

  return { current, handleToggle }
}

React 16.8 or higher

  • Name
    initialValue
    Type
    boolean
    Required
    required
    Description

    The initial value of the boolean.

  • Name
    current
    Type
    boolean
    Description

    The current value of the boolean.

  • Name
    handleToggle
    Type
    function
    Description

    Toggle the boolean value.

import { useToggle } from './hooks/useToggle'

const App = () => {
  const { current, handleToggle } = useToggle(false)

  return (
    <div>
      <p>Current value: {current ? 'True' : 'False'}</p>
      <button onClick={handleToggle}>Toggle value</button>
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Implementing a toggle switch for enabling/disabling a dark mode feature in a web application
  • Creating a collapsible section or accordion component with expand/collapse functionality
  • Adding a toggle button to show/hide additional details or information in a user profile view
  • Developing a toggle switch for switching between different view modes (e.g., grid view vs. list view) in a product catalog