Blog>
Snippets

Nested Selectors for Complex State Shapes

Provide an example of how createSelector can be used to handle nested state objects by extracting and memoizing part of the state, like user preferences in a settings sub-state.
import { createSelector } from 'reselect';

// Assume we have a complex state shape
const state = {
    settings: {
        userPreferences: {
            theme: 'dark',
            notifications: true,
            language: 'en'
        }
    }
    // ... other state slices
};
This code sets up an example state shape with a nested userPreferences object inside settings.
// Input selector: gets the settings slice from the state
const selectSettings = state => state.settings;
This input selector retrieves the settings slice of the state where user preferences are nested.
// Input selector: gets the user preferences from the settings slice
const selectUserPreferences = createSelector(
    [selectSettings],
    settings => settings.userPreferences
);
This input selector is created using createSelector to memoize the operation of selecting user preferences from the settings slice.
// Output selector: gets the theme preference from the user preferences
const selectThemePreference = createSelector(
    [selectUserPreferences],
    userPreferences => userPreferences.theme
);
This output selector uses selectUserPreferences as an input selector and further extracts the theme preference.
const theme = selectThemePreference(state); // Returns 'dark'
console.log(theme);
This code demonstrates how to use the selectThemePreference selector to get the current theme preference, which would log 'dark' to the console.