← Back to all snippets
JAVASCRIPT

Simplify Boolean State with the useToggle Hook

Create a useToggle React hook for effortlessly managing simple boolean state, providing a `toggle` function along with the current state for clear, concise logic.

import { useState, useCallback } from 'react';

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

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

  return [value, toggle];
}
/*
// Example usage:
function Accordion() {
  const [isOpen, toggleOpen] = useToggle(false);

  return (
    <div>
      <button onClick={toggleOpen} style={{ padding: '10px', fontSize: '16px' }}>
        {isOpen ? 'Hide Content' : 'Show Content'}
      </button>
      {isOpen && (
        <div style={{ border: '1px solid #ccc', padding: '15px', marginTop: '10px' }}>
          This is the accordion content that can be toggled on or off.
        </div>
      )}
    </div>
  );
}
*/
How it works: The useToggle hook provides a simple, reusable way to manage boolean state. It takes an optional `initialValue` (defaulting to `false`) and returns the current boolean `value` and a `toggle` function. Calling `toggle` flips the `value` from `true` to `false` or vice-versa, simplifying common UI patterns like toggling visibility of modals, dropdowns, or checkboxes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs