Blog>
Snippets

Utilizing createSelector for Enhanced Selector Performance

Showcase the use of createSelector to create a memoized selector, explaining how weakMapMemoize underpins performance optimizations.
import { createSelector } from '@reduxjs/toolkit';

// Assuming we have a part of the state that holds user details
const selectUser = state => state.user;

// And another part that holds the posts
const selectPosts = state => state.posts;

// A memoized selector to derive the posts for the current user
// The weakMapMemoize function is used implicitly in createSelector here
const selectUserPosts = createSelector(
  [selectUser, selectPosts],
  (user, posts) => posts.filter(post => post.userId === user.id)
);
This code imports the createSelector function from Redux Toolkit and creates two basic selectors to access the user and posts slices of the Redux state. It then defines a memoized selector 'selectUserPosts' which derives the posts for the current user. The createSelector function uses weakMapMemoize implicitly, which optimizes the performance by memoizing the results based on the arguments' references. It only recalculates when the inputs have changed reference, reducing unnecessary recalculations.