Start learning free

LESSON 68 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

State in JavaScript

Practice

Until now your components drew the same thing every time. To show a number that changes when a visitor clicks, a component needs state: a value React keeps for it between draws. You get one from the hook useState. It takes the starting value and gives back a pair: the current value and a set function that changes it.

Here is a like button, a different component:

function LikeButton() {
  const [likes, setLikes] = useState(0);
  return <button onClick={() => setLikes(likes + 1)}>Likes: {likes}</button>;
}

On a click, setLikes(likes + 1) stores the new value and React calls the component again. In that new draw, likes is 1, so the button says Likes: 1. A plain variable changed on a click would not do this: nothing tells React to draw again, and each draw runs the function from the top.

The given ProductCard.jsx puts a QuantityPicker in every product that is in stock, and each picker keeps its own quantity. The check must see:

> open the page
  article "Mug"   text: Quantity: 1   button: +
> click "+" in "Mug"     Quantity: 1 → 2
> click "+" in "Mug"     Quantity: 2 → 3
> click "+" in "Plant"   Quantity: 1 → 2

Your task: in src/QuantityPicker.jsx, make a state variable quantity with setQuantity, starting at 1. Show it in a span as Quantity: 1, and add a + button that adds 1 to it.


Assignment
Follow the Coding Tutorial to give the QuantityPicker its own quantity with useState, show it, and raise it with a + button.


Hint
Call useState at the top of the function, before return. onClick gets a function, an arrow like () => …, that React calls when the button is clicked.


STEP 1 OF 3
    Ctrl + Enter to check

    React First State 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