useReducer

The problem. Several pieces of state that always change together. Loading, error and results are the standard example: every one of them has to be set correctly on every transition, and forgetting one leaves the interface in a state that should not exist, such as loading and error at the same time.

What a reducer does. It moves those transitions into one plain function that takes the current state and an action, and returns the next state. Every transition is written once, in one place, where you can read them side by side.

The reducer is an ordinary function, so it can be tested without rendering anything.

Try it

Try to reach a state where loading is true and error is set. You cannot, and that is the guarantee a reducer buys you.

loading editor…

loading React…

Click through the three actions. Loading and error can never both be set, because no transition produces that.

◈ Graded Component

Build a reducer-driven status display. Using useReducer, manage loading, error and items together. A button with id start begins loading, id ok succeeds with two items, and id fail sets an error. Show the current state in an element with id state: Loading while loading, the error text when there is an error, and N items on success. Starting must always clear a previous error.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 3 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back