Lesson 6 of 8

Derived state

Goal

Compute it, don't store it

01

Explanation

Some values aren't state but a result computed from it. The item count and the cart total are both computed from the items, and if you store them in state next to the items, the same information lives in two places, and every piece of code that changes the items has to update them too.

You won't always remember to. In the code below, adding updates both numbers but removing forgets them, so the cart shows the wrong figures. That's one of the most common UI bugs, and one of the hardest to track down.

The rule here is: store as little as you can and compute the rest when you render. Running reduce over a few dozen items is far cheaper than a single bug caused by two values that weren't updated together.

02

Your task

Remove count and total from state and from the listeners, and compute them inside render() from state.items: the count is the sum of the quantities in qty, and the total is the sum of price × qty.

Checks

5 checks
  1. The state doesn't store what can be computed from it
  2. The count is the sum of the quantities and the total is correct
  3. Adding keeps both numbers correct
  4. Removing keeps both numbers correct
  5. Any change to the items shows up on the next render
03

Hints

0/3
index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.