← Back to all snippets
JAVASCRIPT

Building a Simple `useToggle` Hook

Create a custom React `useToggle` hook for managing boolean state with a simple toggle function, enhancing component reusability.

import { useState, useCallback } from 'react';

function useToggle(initialState = false) {
  const [state, setState] = useState(initialState);

  const toggle = useCallback(() => setState(prev => !prev), []);

  return [state, toggle];
}

// Example Usage:
// function MyComponent() {
//   const [isOn, toggle] = useToggle(false);
//   return (
//     <button onClick={toggle}>
//       {isOn ? 'ON' : 'OFF'}
//     </button>
//   );
// }
How it works: The `useToggle` hook provides a convenient way to manage a boolean state. It uses `useState` for the actual state and `useCallback` to memoize the `toggle` function, preventing unnecessary re-renders of child components that depend on `toggle`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs