Start learning free

LESSON 70 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

State Changes on the Next Draw in JavaScript

Practice

A set function doesn't change the variable you are holding. It tells React the new value, and React calls your component again: only in that next draw does the state have the new value. Inside one draw, state is a snapshot: it keeps the same value until the draw and its handlers are done.

So asking twice with the value doesn't add twice. In another component:

function likeTwice() {
  setLikes(likes + 1);   // likes is 0: asks for 1
  setLikes(likes + 1);   // likes is still 0: asks for 1 again
}

To build on the newest value, pass an updater function instead, like setLikes((n) => n + 1). React queues it and calls it with the newest value, so a second updater gets the result of the first. A console.log of the state in the same handler still prints the value of the draw that is running.

The check clicks "Add 2" in the Mug twice and must see:

> click "Add 2" in "Mug"
  console.log: quantity in this draw: 1
  Quantity: 1 → 3
> click "Add 2" in "Mug"
  console.log: quantity in this draw: 3
  Quantity: 3 → 5

Your task: in src/QuantityPicker.jsx, add a handler addTwo and an Add 2 button that calls it. In addTwo, call setQuantity twice with the updater (q) => q + 1, then log "quantity in this draw:" and quantity.


Assignment
Follow the Coding Tutorial to add an Add 2 button whose handler raises the quantity by 2 with two updater calls and logs the snapshot.


Hint
An updater is a function you pass to the set function: setQuantity((q) => q + 1). The log goes under both calls, and it still prints the quantity of the draw that is running.


STEP 1 OF 5
    Ctrl + Enter to check

    React State Snapshot in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free