Blog>
Snippets

Implementing Memoized Selectors with Reselect

Demonstrate the creation of memoized selectors using the Reselect library to efficiently derive data from the Redux store, which can be used to calculate aggregated metrics without unnecessary recalculations.
import { createSelector } from 'reselect';

// Example state
const shopItemsSelector = state => state.shop.items;
const taxPercentSelector = state => state.shop.taxPercent;

// Creating a memoized selector for calculating subtotal
const subtotalSelector = createSelector(
  shopItemsSelector,
  items => items.reduce((subtotal, item) => subtotal + item.value, 0)
);

// Creating a memoized selector that uses the subtotal and taxPercent to calculate total
const totalSelector = createSelector(
  subtotalSelector,
  taxPercentSelector,
  (subtotal, taxPercent) => subtotal + (subtotal * (taxPercent / 100))
);

// When you use these selectors with Redux's mapStateToProps,
// Reselect will only recalculate the totals if the relevant state changes, i.e.,
// the items or the taxPercent, thus preventing unnecessary recalculations.
This code creates two memoized selectors using the Reselect library. The `subtotalSelector` calculates the subtotal of all shop items, and the `totalSelector` calculates the total including tax. These selectors only recompute when their input selectors return new values, reducing unnecessary recalculations in a Redux application.