JAVASCRIPT

React `useToggle` Hook for Managing Boolean States

Simplifies boolean state management in React components, providing a straightforward way to toggle true/false values with minimal code and improved readability.

import { useState, useCallback } from 'react';

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

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

  return [value, toggle];
};

export default useToggle;
How it works: The `useToggle` hook encapsulates a boolean state, returning the current value and a `toggle` function. The `toggle` function uses `useCallback` to ensure it's stable across re-renders, preventing unnecessary re-creations and optimizing performance for child components that receive it as a prop. It provides a clean and reusable way to manage on/off or true/false states.

Need help integrating this into your project?

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

Hire DigitalCodeLabs