AI Hints
Home›React Tutorial›Updating State
React · Lesson 22 of 120

Updater Functions

Prev => next.

⏱ 2 min read▶ Video at 17:00🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Because state is a snapshot, setting it several times in one click can surprise you. Passing a function to the setter fixes that. It receives the latest value, and returns the next one.

  • Several sets
  • A surprise
  • Pass a function

Adding three at once

The first button sets count plus one, three times, but each call sees the same old count. The second button passes an updater function three times, and each one builds on the last. We click each button once. Run it.

App.jsxjsx
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  const [better, setBetter] = useState(0);

  return (
    <div>
      <button id="a" onClick={() => { setCount(count + 1); setCount(count + 1); setCount(count + 1); }}>
        Snapshot: {count}
      </button>
      <button id="b" onClick={() => { setBetter(c => c + 1); setBetter(c => c + 1); setBetter(c => c + 1); }}>
        Updater: {better}
      </button>
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#a"}, {"click": "#b"}]

When to use updaters

Use an updater whenever the new value depends on the old one, like adding one. It's always correct, even with several updates in a row. Name the parameter after the state, or just use its first letter.

keyvalue
New from olduse an updater
FormsetX(x => x + 1)
Alwayscorrect
Plain valuefine for replacing

Summary

Pass an updater function when the next state depends on the previous one. Next, state with objects.

Key takeaways
  • setCount(c => c + 1)
  • Latest value
  • Safe
Next up: State with Objects — copy, don't change