Blog>
Snippets

Migrating to createEntityAdapter for Normalized State Management

Demonstrate how to refactor a portion of a Redux state that contains an array of objects into a normalized state using createEntityAdapter from RTK 2.0.
import { createSlice, createEntityAdapter } from '@reduxjs/toolkit';

// Assume we have an array of users like this:
// const users = [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }];

// First, create an adapter for the users
const usersAdapter = createEntityAdapter();
This code imports the necessary functions from RTK and sets up an entity adapter for a users array using default configurations.
// Then, define a slice using the adapter to make a normalized state
const usersSlice = createSlice({
  name: 'users',
  initialState: usersAdapter.getInitialState(),
  reducers: {
    // Define reducers using the adapter's updateOne, addOne, etc.
    addUser: usersAdapter.addOne,
    updateUser: usersAdapter.updateOne,
    removeUser: usersAdapter.removeOne
  }
});
This code defines a slice with an initial state from the users adapter, which is normalized. It also includes reducers for adding, updating, and removing users using methods provided by createEntityAdapter.
// Create selector hooks
export const {
  selectAll: selectAllUsers,
  selectById: selectUserById,
  selectIds: selectUserIds
} = usersAdapter.getSelectors(state => state.users);
This code creates customized selector hooks to select all users, a user by ID, or the user IDs from the normalized state.
// Integrate the slice into the store
import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer: {
    users: usersSlice.reducer
  }
});
This code integrates the users slice into the redux store using RTK's configureStore method.
// Using the addUser reducer in a component
// dispatch(usersSlice.actions.addUser({ id: '3', name: 'Dave' }));
An example of how to dispatch the addUser action in a React component.