Start learning free

LESSON 80 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Effects: After the Draw

Practice

When state changes, React draws your component again: it calls the function and works out what the screen should show. A value like the number of things in the cart can be worked out right there, during the draw, from the state.

Some code changes things outside the page React draws: the tab's title, the browser's storage, a timer. That code goes in an effect. useEffect takes a function, which React runs after the draw is on the screen, and an array of dependencies: React runs the effect after the first draw, then again after each draw in which one of them changed.

useEffect(() => {
  localStorage.setItem("lastSearch", query);
}, [query]);

Here, each time query changes, the browser keeps the new search. When it stays the same, React skips the effect.

The check opens the page, clicks Add to cart on the Mug twice, and reads the tab's title after each step. Your page must print:

> open the page
  text: Cart (0)
> the tab's title
  Corner Shop (0)
> click "Add to cart" in "Mug"
  + text: Cart (1)
> the tab's title
  Corner Shop (1)
> click "Add to cart" in "Mug"
  + text: Cart (2)
> the tab's title
  Corner Shop (2)

Your task: in src/App.jsx, work out count, the number of things in the cart, and show it under the heading as Cart (0). Then add an effect, with [count] as its dependencies, that sets document.title to Corner Shop (0) with the current count.


Assignment
Follow the Coding Tutorial to count the things in the cart, show the count on the page, and keep the tab's title in step with it from an effect.


Hint
document.title is a plain property: you set it with =. The dependencies are the second argument of useEffect, after the function.


STEP 1 OF 4
    Ctrl + Enter to check