Sub topic 13
Normalized collections with createEntityAdapter
This chapter assumes you can write a slice with createSlice, build selectors, and read state with useSelector. It also assumes you understand why state shape matters, as covered in the earlier chapters.
The problem with arrays of items
Storing a collection as an array is simple. It becomes awkward when you need to find, update or remove one item. Finding a user by id means scanning the whole array. Updating means mapping over it. If the same item appears in several places, copies can drift apart.
Normalized state fixes this. You store each item once in an object keyed by id, and keep a separate array of ids for ordering.
{
ids: [1, 2],
entities: {
1: { id: 1, name: 'Ada' },
2: { id: 2, name: 'Grace' },
},
}Lookup by id is now a direct property read. Updating one item changes one entry.
What createEntityAdapter provides
createEntityAdapter generates this shape for you. It also supplies reducer functions that maintain it and selectors that read it.
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
const usersAdapter = createEntityAdapter()
const usersSlice = createSlice({
name: 'users',
initialState: usersAdapter.getInitialState(),
reducers: {
userAdded: usersAdapter.addOne,
usersReceived: usersAdapter.setAll,
},
})
export const { selectAll: selectAllUsers, selectById: selectUserById } =
usersAdapter.getSelectors((state) => state.users)
export const { userAdded, usersReceived } = usersSlice.actions
export default usersSlice.reducerThree parts matter here:
getInitialState()returns{ ids: [], entities: {} }. You can pass an object to add extra fields, such asgetInitialState({ status: 'idle' }).- Adapter methods like
addOneandsetAllhave the signature of a case reducer. You can assign them directly inreducers, as above, or call them inside your own reducer withstate. getSelectorstakes a function that finds the adapter's slice of state, and returns ready-made selectors.
Common reducer methods
| Method | Effect |
|---|---|
| `addOne`, `addMany` | Add items. Existing ids are ignored. |
| `setOne`, `setMany`, `setAll` | Add or replace items. `setAll` replaces the whole collection. |
| `upsertOne`, `upsertMany` | Add new items, and shallow-merge into existing ones. |
| `updateOne`, `updateMany` | Apply `{ id, changes }` to existing items. |
| `removeOne`, `removeMany`, `removeAll` | Remove items by id, or all items. |
Note that addOne silently does nothing when the id already exists. If you want "insert or update", use upsertOne.
Generated selectors
getSelectors returns selectIds, selectEntities, selectAll, selectTotal and selectById. Because selectAll is memoized, it returns the same array until the entities change. That makes it safe to use in useSelector.
import { useSelector } from 'react-redux'
import { selectUserById } from './usersSlice'
function UserName({ userId }) {
const user = useSelector((state) => selectUserById(state, userId))
return <span>{user ? user.name : 'Unknown'}</span>
}selectById returns undefined when the id is missing, so handle that case.
Custom ids and sorting
By default the adapter reads the id field. If your data uses another field, pass selectId. To keep ids ordered, pass sortComparer.
import { createEntityAdapter } from '@reduxjs/toolkit'
const booksAdapter = createEntityAdapter({
selectId: (book) => book.isbn,
sortComparer: (a, b) => a.title.localeCompare(b.title),
})With a sortComparer, the adapter inserts items in sorted position, so selectAll returns them in order.
Using it with async data
Adapter methods also work as extraReducers handlers, so a fulfilled thunk can load a collection in one line.
builder.addCase(fetchUsers.fulfilled, usersAdapter.setAll)The adapter method receives state and the action, and uses action.payload as the data.
Exercise
A reducer must update the email of the user with id 7 without touching other users. Which adapter method fits, and what argument does it take?
Show answer
Use updateOne. It takes an object of the form { id: 7, changes: { email: '[email protected]' } }. Only the fields listed in changes are merged into the existing user.
Exercise
You call addMany with a user whose id already exists in state. The stored user does not change. Why, and which method would replace or merge it?
Show answer
addMany ignores items whose ids already exist. Use setMany to replace the stored item, or upsertMany to shallow-merge the new fields into it.