A simple React hook to toggle between boolean states.
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];
}
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.
You can pass true to start with a visible state:
const [showPassword, togglePassword] = useToggle(true);
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.