← Back to React, page 5

react-0087 · Hard senior

How do createEntityAdapter and createSelector help structure large Redux state, and why normalize data?

createEntityAdapter stores collections in a normalized shape ({ ids, entities }) and generates reducers (addOne, setAll, updateOne, removeOne) and selectors (selectAll, selectById, selectIds). Normalization gives O(1) lookups and one source of truth per item, so updates do not need to search arrays. createSelector builds memoized derived data, so components receive the same reference until the inputs change.

Full answer

Storing a list as an array makes updates and lookups require a scan, and the same item can appear in several arrays that drift apart. A normalized shape keeps each item once: entities is an object keyed by id and ids is the order. Other places reference items by id.

createEntityAdapter() encodes this shape. You may pass selectId (if the id field is not id) and sortComparer (to keep ids sorted). The adapter gives reducer helpers that work directly with Immer drafts: addOne, addMany, setAll, updateOne, upsertOne, removeOne. Use them as case reducers, or call them inside your own reducer with the state. adapter.getInitialState() creates the empty structure and can carry extra fields such as status.

adapter.getSelectors((state) => state.students) returns selectAll, selectById, selectIds, selectEntities and selectTotal, bound to the slice location.

Derived data uses createSelector (from Reselect, re-exported by RTK). It takes input selectors and a result function, and recomputes only when an input result changes by reference. Returning a new filtered array from a plain selector would make useSelector see a new value every time and re-render the component for any store change. A memoized selector returns the same array until relevant data changes. Reselect 5 memoizes with an unbounded cache per argument set by default, so parameterized selectors work, but consider the memory for many distinct arguments.

Rules. Keep selectors next to the slice. Select the smallest slice of data in components. Do not write selectors that create new objects unless they are memoized. In development RTK warns when a selector returns a different result for the same input.

Normalization has a cost: reading nested data requires joins through selectors. Normalize when entities are shared, updated individually or numerous. RTK Query is another option, and it caches per endpoint without normalization.

The example runs the store without a UI to show the state shape and memoization.

jsx
import { configureStore, createEntityAdapter, createSelector, createSlice } from '@reduxjs/toolkit';

const studentsAdapter = createEntityAdapter({
  sortComparer: (a, b) => a.name.localeCompare(b.name),
});

const studentsSlice = createSlice({
  name: 'students',
  initialState: studentsAdapter.getInitialState(),
  reducers: {
    received: studentsAdapter.setAll,
    scoreChanged(state, action) {
      studentsAdapter.updateOne(state, { id: action.payload.id, changes: { score: action.payload.score } });
    },
  },
});

const { received, scoreChanged } = studentsSlice.actions;
const store = configureStore({
  reducer: { students: studentsSlice.reducer, theme: (state = 'light') => state },
});

const { selectAll, selectById } = studentsAdapter.getSelectors((state) => state.students);
const selectPassing = createSelector([selectAll], (students) => students.filter((s) => s.score >= 50));

store.dispatch(
  received([
    { id: 2, name: 'Ravi', score: 45 },
    { id: 1, name: 'Asha', score: 82 },
    { id: 3, name: 'Meera', score: 61 },
  ])
);

console.log('ids in order: ' + JSON.stringify(store.getState().students.ids));
console.log('lookup by id 3: ' + selectById(store.getState(), 3).name);

const first = selectPassing(store.getState());
console.log('passing: ' + first.map((s) => s.name).join(', '));

store.dispatch({ type: 'theme/changed' });
console.log('same array after an unrelated change: ' + (selectPassing(store.getState()) === first));

store.dispatch(scoreChanged({ id: 2, score: 70 }));
const second = selectPassing(store.getState());
console.log('passing after update: ' + second.map((s) => s.name).join(', '));
console.log('new array after a relevant change: ' + (second !== first));

This ran as a script against a store with no UI. Output of the run: ids in order: [1,3,2] lookup by id 3: Meera passing: Asha, Meera same array after an unrelated change: true passing after update: Asha, Meera, Ravi new array after a relevant change: true

Key points

  • Normalized state stores items once in entities and keeps order in ids.
  • The adapter provides reducer helpers and selectors, and an optional sortComparer.
  • createSelector memoizes derived data, returning the same reference when inputs are unchanged.
  • Plain selectors that build new arrays or objects cause extra re-renders.
  • Normalize shared or frequently updated data. Use RTK Query when server caching is enough.

Common mistakes

  • Keeping arrays of objects and searching them on every update.
  • Writing selectors that return new arrays and not memoizing them.
  • Normalizing everything, including data that is never shared or updated.
  • Duplicating the same entity under several slices.
  • Reading nested relations in components instead of in selectors.

Follow-ups

  • When is normalization not worth it?
  • How would you build a parameterized selector like selectByCourse(courseId)?
  • How does RTK Query compare with an entity adapter for server data?

Tips

  • Explain the extra re-render problem of unmemoized selectors. It is the practical reason.
  • Say normalization has costs.
  • Mention RTK Query as the alternative for server state.