Blog>
Snippets

Basic createSelector Usage

Demonstrate how to create a memoized selector with Redux Toolkit's createSelector for a simple derived state, like calculating the total items in a shopping cart.
import { createSelector } from '@reduxjs/toolkit';

// Input selector that gets the items from the state
const selectCartItems = state => state.cart.items;

// Memoized selector for calculating total number of items in the cart
const selectTotalItems = createSelector(
  [selectCartItems],
  (items) => items.reduce((total, item) => total + item.quantity, 0)
);
This code creates two selectors. The first one, selectCartItems, is an input selector that retrieves the cart items array from the Redux state. The second one, selectTotalItems, is a memoized selector created using createSelector. It takes selectCartItems as an input and uses a reduce function to calculate the total number of items in the shopping cart by adding up the quantity of each item.