Blog>
Snippets

Enhancing Selectors with createSelector in RTK 2.0

Refactor an existing selector to use the createSelector utility from Redux Toolkit 2.0, optimizing for memoization and performance.
import { createSelector } from '@reduxjs/toolkit';

// Assume we have a state shape like:
// state = { users: { byId: {}, allIds: [] } }

// Existing simple selector
const selectUserIds = state => state.users.allIds;

// Refactor to use createSelector
const selectUserEntities = state => state.users.byId;
const selectUsers = createSelector(
    [selectUserIds, selectUserEntities],
    (userIds, userEntities) => userIds.map(id => userEntities[id])
);
In this JavaScript code, we first import the `createSelector` function from Redux Toolkit. We then define a simple selector `selectUserIds` that retrieves all user IDs from the state. Next, we define another selector `selectUserEntities` that gets the user entities. Using `createSelector`, we refactor the logic to produce a new selector `selectUsers`, which combines the output of `selectUserIds` and `selectUserEntities` to map user IDs to user entities. This new selector will now be memoized for performance.
<!-- HTML structure -->
<div id='users-list'></div>
This HTML snippet creates a div container with the id 'users-list' where we will later render our list of users fetched from the Redux store using the selector.
/* CSS Styles */
#users-list {
    list-style-type: none;
    padding: 0;
}

#users-list li {
    padding: 5px 10px;
    border-bottom: 1px solid #ccc;
}

/* Hover effect */
#users-list li:hover {
    background-color: #f0f0f0;
}
This CSS snippet styles the user list container. It removes the default list-style-type, adds padding, and defines styles for list items, such as padding and a bottom border. There's also a hover effect to highlight items when mousing over.
import { useSelector } from 'react-redux';

function UsersList() {
    const users = useSelector(selectUsers);

    return (
        <ul id='users-list'>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}
This JavaScript code uses React and Redux hooks to fetch and display the list of user entities. It uses the `useSelector` hook with the `selectUsers` selector we defined earlier to get the current list of users from the Redux store and renders them as list items in an unordered list.