AI Hints
Home›React Tutorial›Events and State
React · Lesson 21 of 120

How State Updates

A new render.

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

When you set state, React doesn't change the variable you're holding. It schedules a new render. In that render, your component runs again, and gets the new value.

  • Set state
  • React schedules a render
  • New value next time

A snapshot of state

Clicking sets the count to count plus one, and then logs count. The log shows the old value, because this render's count never changes. The page shows the new value, from the next render. We click once. Run it.

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

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

  function handleClick() {
    setCount(count + 1);
    console.log("count in this render:", count);
  }

  return <button id="b" onClick={handleClick}>Clicked {count} times</button>;
}
Output
count in this render: 0
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": "#b"}]

One click, step by step

The click calls set count. React schedules a render. The component function runs again. Use state returns the new value. And the page shows it.

  1. Click
  2. setCount
  3. Render again
  4. New value
  5. Page updates

Summary

State is a snapshot for each render. Setting it triggers a new render with the new value. Next, updater functions.

Key takeaways
  • Snapshot
  • Schedule a render
  • New value next
Next up: Updater Functions — prev => next