Sub topic 2
The Redux model: store, actions, reducers and one-way data flow
This chapter explains the working model behind Redux. Later chapters build on it with createSlice and configureStore, so it helps to see the plain pieces first.
Prerequisites assumed: solid JavaScript (ES modules, destructuring, spread syntax), React function components with useState, and a basic grasp of immutability and pure functions.
The core idea
Redux keeps your shared application state in one JavaScript object, held in one place called the store. Components do not change that object directly. They describe what happened, and a pure function works out the next state.
Four pieces make this work:
| Piece | What it is | Rule |
|---|---|---|
| State | A plain JavaScript value, usually an object | Treat it as read-only |
| Action | A plain object describing an event | Must have a `type` string |
| Reducer | A function `(state, action) => newState` | Must be pure |
| Store | The object that holds state and runs the reducer | Created once per app |
Actions: describing what happened
An action is a plain object with a type field. By convention, any data the action carries goes in a field called payload.
const action = { type: 'counter/amountAdded', payload: 5 }The type string follows the pattern domain/eventName. Name it after what happened ("amountAdded"), not after a command ("setCounter"). This keeps the log of actions readable, and it lets several reducers respond to the same event.
An action creator is a function that builds an action object, so you do not retype the shape each time:
const amountAdded = (amount) => ({
type: 'counter/amountAdded',
payload: amount,
})Actions should be serializable. That means they hold only plain values such as strings, numbers, arrays and objects. Do not put class instances, functions or promises in them. Redux DevTools and time-travel debugging depend on this.
Reducers: computing the next state
A reducer takes the current state and an action. It returns the next state. The name comes from Array.prototype.reduce, which has the same shape: (accumulator, item) => newAccumulator.
Reducers must follow three rules:
- Compute the new state only from
stateandaction. - Never modify the existing
state. Return a new copy instead. - Have no side effects. No network calls, no
Math.random(), noDate.now(), no logging that matters.
Given the same inputs, a reducer must always return the same output. That is what makes it easy to test and to replay.
Here is a hand-written reducer, without any Redux library:
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
}
}Three details matter here:
- Default parameter.
state = initialStatesupplies the starting state the first time the reducer runs, whenstateisundefined. - Copying with spread.
{ ...state, value: ... }creates a new object. The old one stays untouched. - The
defaultbranch. For an action the reducer does not recognize, it must return the samestateit received. Every action goes through every reducer, so this branch runs often.
Returning the same reference when nothing changed is useful. React-Redux compares references to decide whether a component needs to re-render.
Why not just mutate?
Writing state.value += 1 and returning state looks simpler. It breaks things, though. The store and React-Redux detect change by comparing references with ===. If you mutate in place, the reference stays the same, so subscribers conclude nothing changed and the UI goes stale. Mutation also destroys the history that DevTools uses. The chapter on Immer shows how Redux Toolkit lets you write mutating-looking code safely.
The store: holding state and running the reducer
The store holds the current state, accepts actions, and notifies subscribers when state changes. It exposes three main methods:
store.getState()returns the current state.store.dispatch(action)sends an action to the reducer.store.subscribe(listener)registers a callback that runs after each dispatch.
The following example runs as plain Node.js with only the redux package installed. legacy_createStore is the old core API. Redux Toolkit's configureStore, covered in a later chapter, replaces it in real applications. Using it here keeps the model visible.
import { legacy_createStore as 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())
})
console.log('initial', store.getState())
store.dispatch({ type: 'counter/incremented' })
store.dispatch({ type: 'counter/amountAdded', payload: 5 })
store.dispatch({ type: 'something/unknown' })
unsubscribe()The output is:
initial { value: 0 }
state is now { value: 1 }
state is now { value: 6 }
state is now { value: 6 }The unknown action still triggers the subscriber, because the store notifies after every dispatch. The state value is unchanged, since the reducer returned the same object. Libraries such as React-Redux compare the old and new state to skip needless work.
On creation, the store dispatches an internal initialization action so each reducer can return its initial state. That is how initial { value: 0 } appears before any of your own actions.
One-way data flow
Redux data moves in a single loop. Nothing in the view writes to state directly.
In steps:
- The UI renders from the current state.
- Something happens, such as a click. The event handler dispatches an action.
- The store calls the reducer with the current state and that action.
- The reducer returns new state. The store saves it.
- The store notifies subscribers. The UI reads the new state and re-renders.
This is one-way data flow. Data goes down from the store to the UI. Changes go up as actions. Because every change passes through dispatch, you can log each action, replay them, or pause and inspect the state at any step. When a value is wrong, you look at the actions that led to it and the reducer that handled them. There is no other place that could have written it.
Dispatch is synchronous
dispatch runs the reducer immediately and returns after the state has been updated. If you call store.getState() right after store.dispatch(...), you see the new state. This differs from React's setState, which batches updates. React-Redux may still batch the resulting re-renders.
Common errors
These are the mistakes learners most often make with the model.
- Mutating state in a reducer. Symptoms: the UI does not update, or DevTools shows no diff. Fix: return a new object, or use Redux Toolkit's
createSlice. - Side effects in a reducer. A
fetchorDate.now()inside a reducer makes it impure. Do the work outside, then dispatch an action with the result. Async thunks, covered later, are the standard tool for this. - Forgetting the default case. A
switchwithoutdefaultreturnsundefinedfor unknown actions. Redux throws an error because a reducer must not returnundefined. - Non-serializable actions or state. Putting a
Date,Map, class instance or function into state breaks DevTools and persistence. Store a timestamp number or an ISO string instead. - Modeling actions as setters. Dispatching
{ type: 'setValue', payload: 6 }pushes logic into components. Dispatching an event such asamountAddedkeeps the logic in the reducer.
Combining reducers
An app has many unrelated pieces of state. Instead of one giant reducer, you write one reducer per area and combine them. Each receives only its own part of the state.
import { combineReducers, legacy_createStore as createStore } from 'redux'
function todosReducer(state = [], action) {
switch (action.type) {
case 'todos/added':
return [...state, action.payload]
default:
return state
}
}
function filterReducer(state = 'all', action) {
switch (action.type) {
case 'filter/changed':
return action.payload
default:
return state
}
}
const rootReducer = combineReducers({
todos: todosReducer,
filter: filterReducer,
})
const store = createStore(rootReducer)
store.dispatch({ type: 'todos/added', payload: { id: 1, text: 'Learn Redux' } })
console.log(store.getState())This prints:
{ todos: [ { id: 1, text: 'Learn Redux' } ], filter: 'all' }The keys you pass to combineReducers become the keys of the state object. Every action still goes to every reducer, and each decides whether it cares. This is also what lets two reducers react to one action, a technique the extraReducers chapter uses.
What Redux Toolkit changes
Everything above is the real mechanism, and Redux Toolkit keeps it. It removes the boilerplate around it:
createSlicewrites the action types, action creators and reducer together.- Immer lets you write update code that looks like mutation while producing copies.
configureStoresets up the store, DevTools and common safety checks.
You still dispatch actions, and reducers still compute new state from the old state and an action.
Exercise
A teammate writes this reducer case: case 'cart/itemAdded': state.items.push(action.payload); return state. The cart UI does not update after dispatching. Explain why, and show a corrected case that follows the reducer rules.
Show answer
The reducer mutates the existing state object and returns the same reference. React-Redux compares the old and new state with ===, sees the same object, and concludes nothing changed, so it skips the re-render. The fix is to return new objects along the path that changed: case 'cart/itemAdded': return { ...state, items: [...state.items, action.payload] }.
Exercise
You dispatch { type: 'filter/changed', payload: 'done' } to a store built with combineReducers({ todos: todosReducer, filter: filterReducer }). Which reducers run, and what does todosReducer return for this action?
Show answer
Both reducers run, because every action goes through every reducer. filterReducer matches the type and returns 'done'. todosReducer hits its default case and returns the same state array it received, so the todos part of the state keeps the same reference.