Sub topic 2
The Redux model: store, actions, reducers and one-way data flow
This chapter assumes you know JavaScript modules, pure functions, immutability, and React function components. It explains the model that Redux Toolkit is built on. Later chapters use that model to write slices and configure a store.
The four pieces
Redux keeps application state in one place and changes it in one fixed way.
- The store is an object that holds the whole state tree. It exposes
getState(),dispatch(action)andsubscribe(listener). - An action is a plain object that describes something that happened. By convention it has a
typestring and an optionalpayload. - A reducer is a pure function with the signature
(state, action) => newState. It computes the next state from the current state and an action. - A subscription is a listener function that the store calls after each state update. React-Redux uses subscriptions to re-render components.
Reducers must not mutate their arguments, call APIs, or use random values or the current time. Given the same state and action, they must always return the same result. This is what makes state changes predictable and easy to test.
A store without Toolkit
The following program uses the core redux package directly, so you can see the model with nothing hidden. Install it with npm install redux. Newer Redux versions mark createStore as deprecated, but it still works and shows the model clearly. Redux Toolkit's configureStore replaces it in the next chapters.
import { createStore } from 'redux'
const initialState = { value: 0 }
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'counter/incremented':
return { ...state, value: state.value + 1 }
case 'counter/amountAdded':
return { ...state, value: state.value + action.payload }
default:
return state
}
}
const store = createStore(counterReducer)
const unsubscribe = store.subscribe(() => {
console.log('State is now', store.getState())
})
store.dispatch({ type: 'counter/incremented' })
store.dispatch({ type: 'counter/amountAdded', payload: 5 })
unsubscribe()Running it prints State is now { value: 1 } and then State is now { value: 6 }.
Three details matter here:
- The reducer returns a new object with the spread operator. It never changes
statein place. - The
defaultbranch returns the existingstate. Redux calls the reducer with internal actions at startup, and unknown actions must leave state untouched. - The type string
counter/incrementedfollows thedomain/eventNameconvention. It is written as a past-tense event, because an action describes what happened, not a command.
One-way data flow
Every update travels the same loop. The UI never writes to the store directly. It only dispatches actions.
The steps are:
- Something happens, such as a button click. The handler dispatches an action.
- The store calls the root reducer with the current state and the action.
- The reducer returns the next state, and the store saves it.
- The store calls its subscribers. The UI reads the new state and re-renders.
Because all changes pass through dispatch, you can log, replay or inspect every one of them. This is the basis of Redux DevTools, covered in a later chapter.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Mutating `state` in a hand-written reducer | Subscribers may not see a change, and time-travel debugging breaks | Return a new object or array |
| Forgetting the `default` case | State becomes `undefined` after an unknown action | Return `state` by default |
| Fetching data or calling `Math.random()` inside a reducer | Results are not repeatable | Do side effects outside the reducer |
| Dispatching a non-plain object | Redux throws an error | Dispatch plain objects with a `type` |
Exercise
A reducer handles counter/reset by running state.value = 0; return state. The UI does not update. Why, and how do you fix it?
Show answer
The reducer mutates the existing state object and returns the same reference. The store sees no change, so it treats the state as unchanged and subscribers may skip re-rendering. Return a new object instead: return { ...state, value: 0 }.