Redux & Redux Toolkit
/Advanced
createEntityAdapter()
Definition
An API provided by RTK that automatically generates a set of prebuilt reducers and selectors for performing CRUD operations on normalized state.
Explain Like I'm New
Writing the logic to add, update, and delete items from a normalized `{ ids, entities }` state is tedious. `createEntityAdapter` gives you magic functions like `addOne`, `addMany`, `removeOne`, and `updateOne` out of the box.
Real World Example
You fetch 100 users from an API. You pass the array to `usersAdapter.setAll(state, users)`. It automatically normalizes the array into dictionaries and updates the state.
Common Use Cases
- •Managing lists of relational data
- •Standardizing CRUD operations
Interactive Example
import { createSlice, createEntityAdapter } from '@reduxjs/toolkit'; // 1. Create the adapter const usersAdapter = createEntityAdapter({ // Sort the IDs alphabetically by name by default sortComparer: (a, b) => a.name.localeCompare(b.name), }); // 2. Create the slice const usersSlice = createSlice({ name: 'users', // 3. Initialize state with { ids: [], entities: {} } initialState: usersAdapter.getInitialState(), reducers: { // 4. Use the magic prebuilt reducers! userAdded: usersAdapter.addOne, usersReceived: usersAdapter.setAll, userDeleted: usersAdapter.removeOne, }, });
Interview Questions
basic
- What shape does `createEntityAdapter` enforce on your state slice?
intermediate
- Does `createEntityAdapter` also generate selectors for you?