Start learning free

LESSON 74 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

Share State: Lift It Up in JavaScript

Practice

State belongs to the component that calls useState. Its parent can't read it, and its siblings can't either. When two parts of the page need the same value, you lift the state up: you keep it in the closest component that sits above both of them.

The shop needs this for the cart. The Add to cart buttons are drawn deep down, in each ProductCard. The line Cart (2) is drawn at the top, in App. So the count lives in App. Data goes down as props, and events come up as function calls: App passes a function down, and the card calls it on a click.

Here is the same idea on a blog post with a Like button:

function LikeButton({ onLike }) {
  return <button onClick={onLike}>Like</button>;
}

function Post() {
  const [likes, setLikes] = useState(0);

  function addLike() {
    setLikes(likes + 1);
  }

  return (
    <article>
      <p>{likes} likes</p>
      <LikeButton onLike={addLike} />
    </article>
  );
}

Pass the function itself, onLike={addLike}, without parentheses: with them, it would run while React draws, not on the click. In the shop, the given ProductList already hands onAdd on to every card, and the card calls onAdd(product).

The check opens the page and clicks two buttons:

> open the page                  →  text: Cart (0)  …  text: 8 products
> click "Add to cart" in "Mug"   →  - text: Cart (0)   + text: Cart (1)
> click "Add to cart" in "Lamp"  →  - text: Cart (1)   + text: Cart (2)

Your task: in src/App.jsx, keep a cartCount state, show it as Cart (…) under the heading, write addToCart to raise it by one, and give it to a ProductList as onAdd.


Assignment
Follow the Coding Tutorial to lift the cart count up into App and pass addToCart down to the product cards.


Hint
Write onAdd={addToCart}, the function's name without parentheses: the card calls it later, when its button is clicked.


STEP 1 OF 5
    Ctrl + Enter to check

    React Lift 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