Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Beginner

Reducers

Definition

Pure functions that take the current state and an action, and return a new state result. `(state, action) => newState`.

Explain Like I'm New

The accountant. The accountant looks at your Current Balance (state), looks at your Deposit Slip (action), does the math in their head, and writes down the New Balance (new state). They NEVER scribble over the old balance, they always write a brand new line.

Real World Example

A massive `switch` statement that looks at the `action.type`. If it says 'LOGOUT', it returns `{ user: null }`. If it says 'LOGIN', it returns `{ user: action.payload }`.

Common Use Cases

  • •Calculating state changes securely and predictably

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Can a Reducer modify the original `state` object passed into it?

intermediate

  • Why must a Reducer return the current `state` as a default fallback?

Flash Cards

Question

Modify original state?

Click to reveal answer
Answer

NEVER. Reducers must perform 'Immutable Updates'. They must make a COPY of the state, modify the copy, and return the copy.

Question

Why default fallback?

Click to reveal answer
Answer

When an Action is dispatched, it is sent to EVERY Reducer in the app. If a specific Reducer doesn't care about that specific Action, it must return the current state unchanged so it doesn't accidentally delete its data.