Toggleable React state with a 1-line useReducer

Published on in JavaScript and React

Say goodbye to useState and a silly toggler function calling the state setter. Be cool and use a tiny reducer instead.

Table of contents

Example: "enabled" state

Typical solution with useState

function Component() {
  const [enabled, setEnabled] = useState(true)
  const toggleEnabled = () => setEnabled((previous) => !previous)

  return <button onClick={toggleEnabled}>Toggle</button>
}

2 lines – so long and verbose!

Cool solution with useReducer

React's useReducer hook takes a reducer function and an initial value:

function Component() {
  const [enabled, toggleEnabled] = useReducer((previous) => !previous, true)

  return <button onClick={toggleEnabled}>Toggle</button>
}

Only 1 line. So cool! 😎

This is a bit cryptic at first, and maybe I wouldn't use it in any "real" code, but I found this intriguing and wanted to share it.

I picked this from TkDodo's blog post Things to know about useState (from the "Bonus 2" section).

Another example: toggling a numeric value

Toggling between 250 and 750:

function Component() {
  const [duration, toggleDuration] = useReducer(
    (previous) => (previous + 500) % 1000,
    250
  )

  return <button onClick={toggleDuration}>Toggle</button>
}

Whoops, 4 lines. 🥲 But I invented this myself! 😄