Skip to content

L19 Actions and reducers

20 minSuggested first: C3 or equivalent

Outcome

Predict a state transition from an action and identify where side effects should be inspected.

Learn

State is the current data the system holds. An action describes an event. A reducer computes the next state from the previous state and an action. In this example, the reducer returns a new object when it handles an action, and the original object for actions it doesn't know. action.type === "add" compares strings exactly, capital letters included.

A store coordinates dispatching actions; middleware around it may handle asynchronous work.

Worked example

Start at { count: 4 }. Dispatch { type: "add", amount: 2 }, then { type: "ping" }. What is the state after each?

JavaScript
function reducer(state, action) {
  if (action.type === "add") {
    return { ...state, count: state.count + action.amount };
  }
  return state;
}
Predict first, then show the worked explanation

The first action returns a new object with count 6. The second isn't handled, so the reducer returns the existing object unchanged. Neither action implies a network request.

Practice and check

Guided practice

Practice, not scored

Starting at a count of 4, apply add with an amount of -1, then add with 3. What is the count?

Choose one answer

Exit check

Counts toward completion

Starting at { count: 4 }, the reducer receives { type: "Add", amount: 1 }. What does it return?

Choose one answer

Common mistake

Assuming syntax that looks like mutation always mutates stored state. Some libraries hand the reducer a draft wrapper; check whether one is in use before concluding anything.

Practice on a real repository

After reviewing L05 Collections and mutation, try the puzzle below. Read what it asks rather than assuming this toy reducer's rule applies.

Related topics: State management

Practice is optional. Solving a puzzle doesn't complete a lesson, and lessons never change a puzzle's points.

References