Blog>
Snippets

Updating createSelector Logic for Refactoring

Illustrate updating the logic within a createSelector callback to accommodate changes in the state shape during refactoring.
import { createSelector } from '@reduxjs/toolkit';

// Initial state shape
const selectUserProfile = state => state.user.profile;
const selectPreferences = createSelector(
  selectUserProfile,
  userProfile => userProfile.preferences
);

// After refactoring, the shape of the state has changed
// Old state shape: { user: { profile: { preferences: {...} } } }
// New state shape: { settings: { userPreferences: {...} } }

// To update the selector to match the new state shape, we redefine our base selector:
const selectUserPreferences = state => state.settings.userPreferences;

// And then update the createSelector call to use the new base selector
const selectPreferencesRefactored = createSelector(
  selectUserPreferences,
  userPreferences => userPreferences
);
This code demonstrates how to update a selector created with createSelector from Redux Toolkit when the shape of the state changes. The initial state has user preferences nested within a 'user.profile' object. After the refactor, preferences are now directly under a 'settings' property. We first redefine the base selector to point to the new location of user preferences, and then update the createSelector call to use this new base selector, maintaining memoization and performance benefits.