JAVASCRIPT

Simplify Boolean State Management with a useToggle Hook

Create a concise useToggle React hook to effortlessly manage boolean states, providing a simple function to toggle values and optional setters for true/false.

import { useState, useCallback } from 'react';

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

  const toggle = useCallback(() => {
    setValue(prevValue => !prevValue);
  }, []);

  // Return value and functions to toggle, set true, set false
  return [value, toggle, () => setValue(true), () => setValue(false)];
}

// Example Usage:
// function MyToggleComponent() {
//   const [isOn, toggle, setOn, setOff] = useToggle(false);
//   return (
//     <div>
//       <p>State: {isOn ? 'ON' : 'OFF'}</p>
//       <button onClick={toggle}>Toggle</button>
//       <button onClick={setOn}>Set ON</button>
//       <button onClick={setOff}>Set OFF</button>
//     </div>
//   );
// }
How it works: The `useToggle` hook provides a simple and reusable way to manage boolean state in your React components. Instead of manually calling `!state` or writing separate `setTrue` and `setFalse` functions, this hook gives you a clear `toggle` function, along with optional `setOn` and `setOff` functions, making your code cleaner and more readable for common boolean operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs