Sub topic 8
Choosing what goes in Redux and shaping the state
This chapter assumes you can write a slice with createSlice, read the store with useSelector, and know the difference between local component state and shared state. Here you decide which data belongs in the Redux store and how to lay it out so reducers and selectors stay simple.
Not all state is the same kind of state
A React app holds several kinds of state, and each kind has a natural home.
| Kind of state | Example | Usual home |
|---|---|---|
| Local UI state | Whether a dropdown is open, text in an input being typed | `useState` in the component |
| Shared client state | The signed-in user's preferences, a shopping cart, a multi-step wizard | Redux |
| Server cache | A list of products fetched from an API | RTK Query (or another cache library) |
| URL state | Current page, search query, selected tab in the address | The router |
| Form state | Field values, validation errors, touched flags | A form library or local state |
The common mistake is to put everything in Redux because it is available. Server data copied into a slice by hand needs loading flags, error handling, refetching, and invalidation, all written by you. A cache library already does that work, and later chapters cover RTK Query for it.
Questions that decide it
The official Redux style guidance reduces to a few questions. A "yes" to any of them suggests Redux is a good fit.
- Do other, distant parts of the app need this data?
- Do you need to create more derived data from it?
- Is the same data used by many components?
- Is there value in being able to restore this state at a point in time, for example when debugging with time travel?
- Do you want to keep this state when components unmount and remount, such as when switching routes?
If every answer is "no", keep the state local. Moving local state into Redux later is cheap. Removing it from Redux after dozens of components depend on it is not.
Keep the state minimal
Once you have decided something belongs in Redux, store the smallest set of facts from which everything else can be computed. Three habits help.
Do not store what you can derive
A filtered list, a count of completed items, or a "has errors" flag can all be computed from other state. If you store them, you must update them in every reducer that touches the source data, and sooner or later one reducer forgets. Compute them in selectors instead (the previous chapter covers createSelector).
Store ids, not copies
Suppose the user selects a todo. Storing a copy of the todo object creates two versions of the same data, and editing one leaves the other stale. Store the id and look the object up when you need it.
// Fragile: selectedTodo is a copy that can drift from items
const fragileState = {
items: [{ id: 1, title: 'Write chapter', completed: false }],
selectedTodo: { id: 1, title: 'Write chapter', completed: false },
visibleTodos: [{ id: 1, title: 'Write chapter', completed: false }],
}
// Better: one source of truth, plus ids and settings
const betterState = {
items: [{ id: 1, title: 'Write chapter', completed: false }],
selectedId: 1,
filter: 'all',
}Model status as one value
Several booleans such as isLoading, isError, and isSuccess can describe combinations that should never exist, like loading and failed at the same moment. A single status string allows only valid states.
import { createSlice } from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: {
items: [],
selectedId: null,
filter: 'all', // 'all' | 'done'
status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
error: null,
},
reducers: {
todoSelected(state, action) {
state.selectedId = action.payload
},
filterChanged(state, action) {
state.filter = action.payload
},
todoToggled(state, action) {
const todo = state.items.find((t) => t.id === action.payload)
if (todo) {
todo.completed = !todo.completed
}
},
},
})
export const { todoSelected, filterChanged, todoToggled } = todosSlice.actions
export default todosSlice.reducer
export const selectSelectedTodo = (state) =>
state.todos.items.find((t) => t.id === state.todos.selectedId)Every reducer here changes one fact. selectSelectedTodo derives the selected object, so toggling a todo can never leave a stale copy behind.
Organize by feature
Each slice should own one area of the app and be named after the feature, such as todos, cart, or auth. Avoid slices named after technical layers like modals or buttons. A feature slice keeps its reducers, its selectors, and its thunks in one folder, so a change to the feature touches one place.
src/
app/
store.js
features/
todos/
todosSlice.js
cart/
cartSlice.jsThe top-level state then reads like a map of the app: state.todos, state.cart, state.auth. Slices stay independent. When one slice must react to another's action, use extraReducers (covered in a later chapter) instead of reaching into the other slice's state.
Keep state serializable
Redux state should consist of plain values: objects, arrays, strings, numbers, booleans, and null. Avoid these:
Dateobjects. Store an ISO string or a timestamp number.MapandSetinstances. Use plain objects and arrays.- Class instances and functions.
- Promises and DOM nodes.
Plain data is what makes DevTools inspection, time travel, and persistence work. configureStore includes a middleware that logs a console warning in development when it finds a non-serializable value in state or in an action. Treat that warning as a design signal, not noise to silence.
// Avoid
dispatch(taskAdded({ title: 'Ship it', due: new Date() }))
// Prefer
dispatch(taskAdded({ title: 'Ship it', due: new Date().toISOString() }))Convert back to a Date inside the component or selector that needs one.
Normalize collections that are looked up by id
If you often find, update, or reference items by id, an array forces a linear scan each time, and nested copies of the same item multiply. Normalization stores items in an object keyed by id, plus an array of ids for order:
const normalized = {
ids: [2, 1],
entities: {
1: { id: 1, title: 'Write chapter', completed: false },
2: { id: 2, title: 'Review chapter', completed: true },
},
}Do this when the collection is large, when items are referenced from several places, or when updates are frequent. For a short list that you only render in order, a plain array is simpler and fine. A later chapter shows createEntityAdapter, which builds this shape and its reducers for you.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Putting every `useState` value in Redux | Extra actions and re-renders for data no one else reads | Keep local state local |
| Hand-copying API responses into slices | You rebuild caching, refetching, and invalidation yourself | Use RTK Query for server data |
| Storing derived values | Duplicates that go stale | Derive them in selectors |
| Storing a copy of an item as "selected" | Two sources of truth | Store the id |
| Storing `Date` or class instances | Serializability warnings, broken persistence | Store plain values |
| Boolean flags for status | Impossible combinations | One `status` string |
Exercise
A product page shows a list of products fetched from /api/products, a "sort by price" dropdown that only this page uses, and a shopping cart that appears in the header on every page. Which of these belong in a Redux slice, and what would you store for the cart if the cart items refer to products?
Show answer
Only the cart belongs in Redux, because the header and other pages share it. The product list is server data and should be handled by RTK Query. The sort dropdown value is local UI state and can live in useState, or in the URL if the sort should survive a reload or be shareable. For the cart, store product ids and quantities, for example { productId: 7, quantity: 2 }, rather than copies of the product objects. Product details are then read from the single cached source, and the cart total is derived in a selector instead of being stored.