Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.4 — State as a Snapshot
React · Example 2 of 3

Send to whoever was chosen when you clicked

The message goes to Alice, because she was selected when Send was clicked. Switching to Bob during the delay changed the next render, not the old one. This is the behaviour you want for a real Send button.

Each render sees a fixed snapshot of state: the values never change while that render's code (including its event handlers and timers) runs, and calling a setter only asks React for a new render with new values.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Predict exactly what this logs when you click once, then explain: ``jsx const [n, setN] = useState(10); function handleClick() { setN(n * 2); console.log(n); setTimeout(() => console.log(n), 100); }

02

Write a DelayedLike button that waits 1 second and then logs Liked post <id> for the post that was open when it was clicked, using a postId state with two buttons to switch posts.

Explain it without notes

01

What does "state is a snapshot" mean?

02

Why does console.log(count) right after setCount(count + 1) print the old value?

03

A Send button waits 3 seconds before sending. The user changes the recipient during the wait. Who gets the message, and why?

04

How do you use the new value in the same handler where you set it?

Send to whoever was chosen when you clicked

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Sending in 500 ms...
Sent "Hello" to Alice
The screen now says: To: Bob