Blog>
Snippets

Optimizing Selector Performance with Memoization

Show a scenario where a selector with expensive computations is optimized using createSelector’s memoization feature, to prevent unnecessary recalculations on state change.
import { createSelector } from '@reduxjs/toolkit';

// Assume a complex state shape
const selectExpensiveData = state => state.expensiveData;

// A hypothetical expensive computation
const computeExpensiveValue = (data) => {
    console.log('Expensive computation running');
    // ... some CPU-intensive operations ...
    return data.reduce((total, item) => total + item.complexCalculation, 0);
};

// Memoized selector using createSelector
export const selectTotalExpensiveValue = createSelector(
    [selectExpensiveData],
    (expensiveData) => computeExpensiveValue(expensiveData)
);
This code defines a memoized selector using createSelector from Redux Toolkit. The computeExpensiveValue performs expensive calculations on the data. createSelector is used to ensure that these calculations are only re-evaluated when selectExpensiveData returns a different value.