JavaScript Snippet

React useToggle Hook

Difficulty: Easy

Boolean state shows up everywhere: modals, drawers, accordions, password visibility, dark mode. The useToggle hook collapses three lines of `useState` plus a setter into one call. This snippet covers the minimal toggle, a value-aware variant that lets callers pin the state to a specific boolean, and an enum-aware version that cycles through any number of states (light / dark / system).

Code Snippets
/

React useToggle Hook

React useToggle Hook

Boolean state shows up everywhere: modals, drawers, accordions, password visibility, dark mode. The useToggle hook collapses three lines of `useState` plus a setter into one call. This snippet covers the minimal toggle, a value-aware variant that lets callers pin the state to a specific boolean, and an enum-aware version that cycles through any number of states (light / dark / system).

JavaScript
Easy
3 snippets
react
hooks
code-template
utility

630 views

16

The hook returns the current boolean alongside a setter that flips it. Using the functional form setOn((v) => !v) is essential: a plain setOn(!on) captures on from render scope and breaks if two toggles fire in the same tick. The signature [value, toggle] mirrors useState so destructuring stays familiar. This is the version you want for password show / hide, drawer open / close, and any one-shot boolean.