JAVASCRIPT

Simple React useToggle Hook for Boolean State

Implement a useToggle custom hook in React to easily manage boolean states, providing a simple function to switch between true and false values.

import { useState, useCallback } from 'react';

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = useCallback((newValue) => {
    setValue(prevValue => typeof newValue === 'boolean' ? newValue : !prevValue);
  }, []);

  return [value, toggle];
}

// Usage example:
// function MyComponent() {
//   const [isOn, toggle] = useToggle(false);
//
//   return (
//     <div>
//       <p>Current state: {isOn ? 'ON' : 'OFF'}</p>
//       <button onClick={() => toggle()}>Toggle</button>
//       <button onClick={() => toggle(true)}>Turn ON</button>
//       <button onClick={() => toggle(false)}>Turn OFF</button>
//     </div>
//   );
// }
How it works: The `useToggle` hook provides a convenient way to manage a boolean state. It initializes a state with `useState` and returns the current boolean value along with a `toggle` function. The `toggle` function, memoized with `useCallback` for performance, flips the boolean state. It can also accept an optional argument to set the state explicitly to true or false.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs