Blog>
Snippets

Chaining Selectors for Computed Values

Showcase the chaining of multiple createSelector functions to compute a value, like a subtotal from a list of products and their quantities in a cart.
import { createSelector } from 'reselect';

// Selector to get the cart items
const selectCartItems = state => state.cart.items;

// Selector to get a specific product's quantity by its id
const selectQuantityById = createSelector(
    [selectCartItems, (state, productId) => productId],
    (items, productId) => items.find(item => item.id === productId)?.quantity || 0
);

// Selector to compute the subtotal of the cart
const selectCartSubtotal = createSelector(
    [selectCartItems],
    items => items.reduce((subtotal, item) => subtotal + item.price * item.quantity, 0)
);
This piece of code imports `createSelector` from the `reselect` library and defines three selectors. The `selectCartItems` selector retrieves the cart items from the state. The `selectQuantityById` selector is a memoized selector that takes the cart items and a product ID, and returns the quantity for that product. The `selectCartSubtotal` selector calculates the subtotal of the cart by multiplying each item's price by its quantity and summing them up.