Sub topic 13
Normalized collections with createEntityAdapter
This chapter assumes you can write a slice with createSlice, read state with useSelector, and write simple selectors. It builds on the ideas in the earlier chapters about state shape and selectors.
The problem with arrays of records
A slice often holds a list of records, such as users, posts, or comments. The obvious shape is an array:
const initialState = {
items: [
{ id: 'u1', name: 'Ada' },
{ id: 'u2', name: 'Grace' },
],
}Arrays work for small lists. They cause trouble as the app grows.
- Finding one record by id means scanning the array. The cost grows with the list length.
- Updating one record means finding its index first, then writing to it.
- The same record can appear in several places, such as a post list and a search result list. The copies drift apart when only one is updated.
- A server response that returns an existing record again can create a duplicate entry unless you check for it.
Normalization addresses these problems. A normalized collection stores each record once, in an object keyed by id. A separate array holds the ids in order.
const normalizedState = {
ids: ['u1', 'u2'],
entities: {
u1: { id: 'u1', name: 'Ada' },
u2: { id: 'u2', name: 'Grace' },
},
}Lookup by id is now state.entities[id]. Updating a record is a single assignment. Other parts of the state refer to the record by id instead of copying it.
What createEntityAdapter provides
createEntityAdapter is a Redux Toolkit function that returns an object with three kinds of helpers for this exact shape:
getInitialStatebuilds the{ ids, entities }object. You can pass extra fields, such as a loading status.- A set of reducer functions for common changes: add, update, upsert, remove, and replace.
getSelectorsbuilds selectors for reading the collection.
You write less code, and the code follows a tested pattern.
A complete slice
The example below uses the adapter in a users slice.
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.reducerSeveral things happen here.
createEntityAdapter()is called with no options. By default it expects each record to have anidfield.getInitialState()returns{ ids: [], entities: {} }.usersAdapter.addOneandusersAdapter.setAllare reducer functions. They have the signature(state, action), so you can assign them directly as case reducers. The action payload is the record (foraddOne) or an array of records (forsetAll).getSelectorstakes a function that finds this slice inside the root state. Here that is(state) => state.users. The returned selectors then work with the full root state.
Dispatching works as you would expect:
import { store } from './store'
import { userAdded, usersReceived } from './usersSlice'
store.dispatch(usersReceived([
{ id: 'u1', name: 'Ada' },
{ id: 'u2', name: 'Grace' },
]))
store.dispatch(userAdded({ id: 'u3', name: 'Linus' }))
console.log(store.getState().users.ids)
// ['u1', 'u2', 'u3']The reducer functions
The adapter's reducers differ in how they treat a record that already exists. Choosing the right one avoids duplicates and lost fields.
| Function | Payload | Behavior |
|---|---|---|
| `addOne` | one record | Adds the record. Does nothing if the id already exists. |
| `addMany` | array or id-keyed object | Adds each record whose id is new. Existing ids are ignored. |
| `setOne` | one record | Adds the record, or replaces the existing one entirely. |
| `setMany` | array or id-keyed object | Same as `setOne` for many records. |
| `setAll` | array or id-keyed object | Discards the whole collection and replaces it. |
| `updateOne` | `{ id, changes }` | Shallow-merges `changes` into an existing record. Does nothing if the id is missing. |
| `updateMany` | array of `{ id, changes }` | Applies several updates. |
| `upsertOne` | one record | Adds the record, or shallow-merges it into the existing one. |
| `upsertMany` | array or id-keyed object | Same as `upsertOne` for many records. |
| `removeOne` | an id | Removes that record. |
| `removeMany` | array of ids | Removes those records. |
| `removeAll` | none | Empties the collection. |
Two points often cause confusion.
First, setOne replaces the record, while upsertOne merges into it. If the server sends back only some fields, setOne drops the fields it did not send. upsertOne keeps them.
Second, updateOne takes a different payload shape. It needs the id and a changes object, not a whole record:
store.dispatch(usersSlice.actions.userUpdated({
id: 'u1',
changes: { name: 'Ada Lovelace' },
}))This assumes you added userUpdated: usersAdapter.updateOne to the reducers object.
Using the adapter inside your own reducers
Each adapter function can also be called on its own, with the draft state as the first argument. This is useful when a reducer needs to do more than one thing.
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
const postsAdapter = createEntityAdapter()
const postsSlice = createSlice({
name: 'posts',
initialState: postsAdapter.getInitialState({ status: 'idle' }),
reducers: {
postsLoaded(state, action) {
postsAdapter.upsertMany(state, action.payload)
state.status = 'succeeded'
},
},
})
export const { postsLoaded } = postsSlice.actions
export default postsSlice.reducerThe state passed to upsertMany is an Immer draft. The adapter functions are designed to work with drafts, so you do not need to return anything.
The argument to getInitialState is merged into the initial object. The state becomes { ids: [], entities: {}, status: 'idle' }.
Using the adapter with extraReducers
The adapter functions fit well with createAsyncThunk. In the extraReducers builder you can pass them directly as the case reducer:
import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit'
export const fetchUsers = createAsyncThunk('users/fetchUsers', async () => {
const response = await fetch('/api/users')
if (!response.ok) {
throw new Error('Request failed')
}
return response.json()
})
const usersAdapter = createEntityAdapter()
const usersSlice = createSlice({
name: 'users',
initialState: usersAdapter.getInitialState({ status: 'idle' }),
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUsers.pending, (state) => {
state.status = 'loading'
})
.addCase(fetchUsers.fulfilled, (state, action) => {
state.status = 'succeeded'
usersAdapter.setAll(state, action.payload)
})
},
})
export default usersSlice.reducerHere the fulfilled case replaces the whole collection with the fetched list. If the app loads data in pages, use upsertMany instead so earlier pages are kept.
Generated selectors
getSelectors returns these selectors:
selectIdsreturns the ordered array of ids.selectEntitiesreturns the id-keyed object.selectAllreturns an array of records in id order.selectTotalreturns the number of records.selectById(state, id)returns one record orundefined.
selectAll is memoized. It returns the same array reference until ids or entities change, so a component using it does not re-render needlessly.
If you call getSelectors() with no argument, the selectors expect the entity state itself, not the root state. This is handy when you already hold a slice's state, for example in a test.
A component can use the generated selectors like any others:
import { useSelector } from 'react-redux'
import { selectAllUsers, selectUserById } from './usersSlice'
function UserList() {
const users = useSelector(selectAllUsers)
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
)
}
function UserName({ userId }) {
const user = useSelector((state) => selectUserById(state, userId))
return <span>{user ? user.name : 'Unknown user'}</span>
}Always handle the undefined result from selectById. A record may not be loaded yet, or may have been removed.
Options: custom ids and sorting
The adapter accepts two options.
import { createEntityAdapter } from '@reduxjs/toolkit'
const booksAdapter = createEntityAdapter({
selectId: (book) => book.isbn,
sortComparer: (a, b) => a.title.localeCompare(b.title),
})selectIdtells the adapter how to find the id when records do not use anidfield.sortComparerkeeps theidsarray sorted. Without it,idsstays in insertion order, andselectAllreturns records in that order.
A sorted adapter has a cost. After each change that affects order, the adapter re-sorts ids. This is fine for hundreds of records. For very large collections, consider whether you need sorting in state, or whether a createSelector that sorts a derived view is a better fit.
Combining the adapter with createSelector
Generated selectors cover simple reads. For derived data, build on them with createSelector:
import { createSelector } from '@reduxjs/toolkit'
import { selectAllUsers } from './usersSlice'
export const selectAdminUsers = createSelector(
[selectAllUsers],
(users) => users.filter((u) => u.role === 'admin')
)Because selectAllUsers is itself memoized, selectAdminUsers recomputes only when the collection changes.
Common errors
- Using
setOnewhere you meantupsertOne. Fields missing from the payload are lost. UseupsertOnefor partial server data. - Passing a whole record to
updateOne. It needs{ id, changes }. A plain record will not update anything. - Forgetting the state selector in
getSelectors. Without it, the selectors expect the entity state, and calling them with the root state returns wrong results. - Mixing ids of different types.
1and'1'become the same key inentities, because object keys are strings, butidskeeps them as given. Use one type consistently. - Storing derived data in the collection. Keep the entity state minimal. Compute counts and filtered lists with selectors.
Decision criteria
Use createEntityAdapter when:
- records have stable unique ids,
- the app looks them up or updates them individually, or
- several parts of the UI refer to the same record.
Skip it when the list is small, is replaced wholesale, and is never read by id. A plain array is simpler there. If the data comes from a server and you only display and cache it, RTK Query already manages a cache for you, and you may not need the records in a slice at all.
Exercise
A server returns { id: 'u1', role: 'admin' } for a user whose stored record is { id: 'u1', name: 'Ada', role: 'user' }. You want the result to be { id: 'u1', name: 'Ada', role: 'admin' }. Which adapter function do you call, and why would setOne be the wrong choice?
Show answer
Call upsertOne (or updateOne with { id: 'u1', changes: { role: 'admin' } }). Both merge the new fields into the existing record. setOne replaces the whole record, so name would be lost and the result would be { id: 'u1', role: 'admin' }.
Exercise
You build usersAdapter with getSelectors() and no argument, then call selectAll(store.getState()). What goes wrong, and how do you fix it?
Show answer
Without a state selector, selectAll expects the entity state ({ ids, entities }), but it receives the root state, so it reads the wrong object and returns incorrect or empty results. Fix it by calling usersAdapter.getSelectors((state) => state.users), or by passing store.getState().users to the selector.