Compute the total from the items rather than keeping a second state.
Acceptance criteria
- 1.#total should show 3.
React Tutorial · State and Reducers
These 10 tasks go with the Structuring State chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Most state bugs are structural. If a value can be calculated from another value, storing it means two things that can disagree.” .
1.Derive instead of storingexercise · easy · 10 min
Compute the total from the items rather than keeping a second state.
Passes when: #total should show 3.
2.Group related fieldsexercise · easy · 10 min · practice plan
Keep two related values in one state object.
Passes when: #root should show Ada London.
3.Store an id, not the objectexercise · medium · 10 min · practice plan
Keep the selected id in state and look the item up.
Passes when: #value should show second.
4.One status instead of flagsexercise · easy · 10 min · practice plan
Use a single status string rather than several booleans.
Passes when: #value should show done.
5.Compute a filtered viewexercise · easy · 10 min · practice plan
Filter the list for display without storing the filtered copy.
Passes when: #count should show 2.
6.Fix the duplicated totalbug fix · medium · 8 min
A stored total goes stale when the list changes.
Passes when: The total should follow the list.
7.Fix the contradictory flagsbug fix · medium · 8 min · practice plan
Two booleans allow an impossible state; use one status.
Passes when: Clicking finish should show done.
8.Fix the copied object in statebug fix · medium · 8 min · practice plan
A stored copy of the selected item goes stale; store the id.
Passes when: Clicking should show second.
9.Fix the state initialised from a propbug fix · easy · 8 min · practice plan
State copied from a prop ignores later prop values.
Passes when: #value should show Ada.
10.Fix the filtered copy stored in statebug fix · medium · 8 min · practice plan
The filtered list is stored, so it never updates with the source.
Passes when: The count should follow the list.
Between them these tasks cover Derived values, Grouping and Single source.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.