Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 41 ยท Middleware and Selectors

createEntityAdapter

Learn how createEntityAdapter stores collections as ids plus entities, generates CRUD reducers and selectors, supports sorting, and how to build the same idea by hand.

Lists of things (posts, users, products) appear in nearly every app. Storing them as arrays works until you need to update one by id, which means scanning the array every time. The recommended Redux shape is normalized: a lookup object entities keyed by id, plus an ids array that holds the order.

createEntityAdapter is a Redux Toolkit helper that gives you that shape together with ready-made reducer functions (addOne, upsertMany, removeOne, ...) and selectors (selectAll, selectById, selectIds). It saves a lot of repetitive code.

Redux Toolkit is not available in the editors here. The real API is shown read-only, and the runnable examples implement a simplified stand-in adapter with the same shape and method names so you can see exactly what it does.

The shape

JavaScript
{
  ids: [3, 1, 2],
  entities: {
    1: { id: 1, title: 'B' },
    2: { id: 2, title: 'C' },
    3: { id: 3, title: 'A' },
  },
}

Lookup by id is O(1), an update touches one object, and ids can be kept sorted. Why this matters for state design is covered in the next chapter section.

The real API (read-only)

JavaScript
// Real Redux Toolkit code (read-only)
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';

const postsAdapter = createEntityAdapter({
  selectId: (post) => post.id,                       // default: entity.id
  sortComparer: (a, b) => b.date.localeCompare(a.date), // keeps ids sorted
});

const postsSlice = createSlice({
  name: 'posts',
  initialState: postsAdapter.getInitialState({ status: 'idle' }), // extra fields allowed
  reducers: {
    postAdded: postsAdapter.addOne,                  // used directly as a case reducer
    postUpdated: postsAdapter.updateOne,             // payload: { id, changes }
    postRemoved: postsAdapter.removeOne,             // payload: id
  },
  extraReducers: (builder) => {
    builder.addCase(fetchPosts.fulfilled, (state, action) => {
      postsAdapter.setAll(state, action.payload);    // or upsertMany to merge
      state.status = 'succeeded';
    });
  },
});

export const {
  selectAll: selectAllPosts,
  selectById: selectPostById,
  selectIds: selectPostIds,
} = postsAdapter.getSelectors((state) => state.posts);

The adapter methods work in two ways: as case reducers (pass them as reducers: { postAdded: postsAdapter.addOne }) or as helpers inside another reducer that receives the Immer draft (postsAdapter.addOne(state, action.payload)).

Method Does
addOne, addMany Add; ignored if the id already exists
setOne, setMany, setAll Add or replace entirely
upsertOne, upsertMany Add or shallow-merge into existing
updateOne, updateMany Merge { id, changes } into existing
removeOne, removeMany, removeAll Delete

A stand-in adapter you can run

This version works on plain objects and returns new state (the real one lets you mutate the draft). It supports sortComparer, so you can watch ids stay ordered.

JS Entity adapter stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice ids is re-sorted after the title of post 2 changed, and addOne ignored the duplicate id.

Selectors generated for you

getSelectors returns selectIds, selectEntities, selectAll, selectTotal and selectById. They are memoized, so selectAll returns the same array until ids or entities change. Pair them with createSelector for derived data:

JavaScript
// Real Redux Toolkit code (read-only)
const selectPostsByAuthor = createSelector(
  [selectAllPosts, (state, authorId) => authorId],
  (posts, authorId) => posts.filter((p) => p.authorId === authorId),
);

In a list component, select only the ids in the parent and let each row select its own entity with selectById. When one post changes, only that row re-renders:

JSX
// Real React-Redux code (read-only)
function PostList() {
  const ids = useSelector(selectPostIds);
  return ids.map((id) => <PostRow key={id} id={id} />);
}
function PostRow({ id }) {
  const post = useSelector((state) => selectPostById(state, id));
  return <li>{post.title}</li>;
}

Relations, custom ids and RTK Query

  • Custom id: supply selectId, for example (user) => user.email.
  • Relations: store ids, not copies. A post keeps authorId, and a selector joins post and user.
  • With RTK Query: use transformResponse: (res) => postsAdapter.setAll(postsAdapter.getInitialState(), res) so the cached data is already normalized, and selectById works on data.
  • Sorting cost: sorting runs on every change of that collection. For very large lists consider sorting in a selector instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the two main parts of the state created by getInitialState()?

    ids is an ordered array, entities is a lookup keyed by id.
  2. 2. How does updateOne differ from setOne?

    updateOne takes { id, changes } and merges; setOne replaces the whole entity.
  3. 3. What does sortComparer do?

    The adapter re-sorts ids whenever the collection changes.
  4. 4. Why select ids in the list and the entity in each row?

    The parent re-renders only when ids change; rows re-render only for their own entity.

Summary

  • Normalized state is ids plus entities, with O(1) lookups and one-object updates.
  • createEntityAdapter gives CRUD reducers and memoized selectors.
  • Adapter methods work as case reducers or as helpers inside others.
  • Use sortComparer for ordering and selectId for custom keys.
  • Select ids in lists and entities in rows to limit re-renders.

Next: Normalizing state shape