avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

useToggle Hook

A simple React hook to toggle between boolean states.

LanguageTypeScript
Last UpdatedApr 22, 2025
use-toggle.ts
import { useCallback, useState } from 'react';

export function useToggle(initial = false): [boolean, () => void] {
  const [value, setValue] = useState(initial);
  const toggle = useCallback(() => setValue(v => !v), []);
  return [value, toggle];
}

Toggling a boolean state is a very common task in React — think of modals, dropdowns, switches, and more. The useToggle hook makes it easier to handle this pattern in a clean and reusable way.

import { useCallback, useState } from 'react';

export function useToggle(initial = false): [boolean, () => void] {
  const [value, setValue] = useState(initial);
  const toggle = useCallback(() => setValue(v => !v), []);
  return [value, toggle];
}

How It Works

  • useState(initial) creates a boolean state initialized with false (or custom value).
  • useCallback memoizes the toggle function to prevent unnecessary re-renders.
  • Each time toggle() is called, it switches the value between true and false.

Example Usage

function ToggleExample() {
  const [isOpen, toggleOpen] = useToggle();

  return (
    <div>
      <button onClick={toggleOpen}>
        {isOpen ? 'Close' : 'Open'} Modal
      </button>
      {isOpen && <div className="modal">Hello from the modal!</div>}
    </div>
  );
}

This replaces repetitive setState(prev => !prev) logic with a reusable abstraction.

Use Cases

  • Show/hide UI components (modals, tooltips, sidebars)
  • Toggle dark/light themes
  • Enable/disable form inputs or buttons
  • Toggle visibility of passwords

With Custom Initial Value

You can pass true to start with a visible state:

const [showPassword, togglePassword] = useToggle(true);

Notes

  • This hook returns a tuple [value, toggleFn], just like useState.
  • The toggle function is memoized, so it can safely be passed to child components.

A tiny utility hook that simplifies one of the most common patterns in React — useToggle helps reduce code noise and keeps your components more readable.

Previous Snippet

useIsMounted Hook

Next Snippet

useLocalStorage Hook