JAVASCRIPT

Simplify Boolean State Management with a Custom useToggle Hook

Streamline the handling of simple boolean states (e.g., toggling a modal, menu visibility, or a checkbox) in React components with a clean and reusable custom useToggle hook.

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

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

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

  // You can also provide specific 'on' and 'off' setters if needed
  const setTrue = useCallback(() => setValue(true), []);
  const setFalse = useCallback(() => setValue(false), []);

  return [value, toggle, setTrue, setFalse];
};

// Example Usage:
const ToggleComponent = () => {
  const [isModalOpen, toggleModal, openModal, closeModal] = useToggle(false);
  const [isMenuExpanded, toggleMenu] = useToggle(true);

  return (
    <div>
      <h1>useToggle Examples</h1>

      <div>
        <h2>Modal Status:</h2>
        <p>Modal is {isModalOpen ? 'Open' : 'Closed'}</p>
        <button onClick={toggleModal}>Toggle Modal</button>
        <button onClick={openModal}>Open Modal</button>
        <button onClick={closeModal}>Close Modal</button>
        {isModalOpen && (
          <div style={{ border: '1px solid #ccc', padding: '10px', marginTop: '10px' }}>
            This is a modal content!
            <button onClick={closeModal} style={{ marginLeft: '10px' }}>Close</button>
          </div>
        )}
      </div>

      <div style={{ marginTop: '20px' }}>
        <h2>Menu Status:</h2>
        <p>Menu is {isMenuExpanded ? 'Expanded' : 'Collapsed'}</p>
        <button onClick={toggleMenu}>Toggle Menu</button>
        {isMenuExpanded && (
          <ul style={{ background: '#eee', padding: '10px', listStyle: 'none' }}>
            <li>Item 1</li>
            <li>Item 2</li>
          </ul>
        )}
      </div>
    </div>
  );
};

const App = () => <ToggleComponent />;
How it works: The `useToggle` hook simplifies managing boolean state in React components. Instead of defining `useState` and a separate `handleClick` function for every boolean, `useToggle` provides a single function `toggle` to flip the boolean value. It can optionally be initialized with a value. For more explicit control, it also provides `setTrue` and `setFalse` functions. This makes components cleaner and more readable when dealing with frequent true/false state changes like modal visibility, menu expansion, or checkbox states.

Need help integrating this into your project?

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

Hire DigitalCodeLabs