JAVASCRIPT

Develop a Custom Hook for Toggling Boolean States

Learn to create a flexible useToggle custom hook in React, simplifying the management of boolean states for UI elements like modals, dropdowns, or feature flags with a single function.

import React, { useState, useCallback } from 'react';

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

  // Memoize the toggle function to prevent unnecessary re-renders
  // if passed down to child components and to ensure stable reference
  const toggle = useCallback(() => {
    setValue(currentValue => !currentValue);
  }, []); // No dependencies needed as it only toggles based on previous state

  return [value, toggle];
}

// Example component using the hook
function ToggableElement() {
  const [isVisible, toggleVisibility] = useToggle(false);
  const [isDarkMode, toggleDarkMode] = useToggle(false);

  return (
    <div>
      <h1>useToggle Hook Example</h1>
      <button onClick={toggleVisibility}>
        {isVisible ? 'Hide Content' : 'Show Content'}
      </button>
      {isVisible && <p>This content is now visible!</p>}

      <div style={{ marginTop: '20px' }}>
        <label>
          <input type="checkbox" checked={isDarkMode} onChange={toggleDarkMode} />
          Enable Dark Mode
        </label>
        <p style={{ background: isDarkMode ? '#333' : '#fff', color: isDarkMode ? '#fff' : '#333', padding: '10px' }}>
          This text changes with dark mode.
        </p>
      </div>
    </div>
  );
}

export default ToggableElement;
export { useToggle }; // Exporting for reuse
How it works: The `useToggle` custom hook provides a simple, reusable way to manage a boolean state (e.g., for showing/hiding elements, enabling/disabling features). It internally uses `useState` to hold the boolean value and returns the current state along with a `toggle` function. The `toggle` function is memoized using `useCallback` to ensure its reference remains stable across re-renders, which is beneficial for performance when passing it as a prop to child components, preventing them from re-rendering unnecessarily.

Need help integrating this into your project?

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

Hire DigitalCodeLabs