Preventing createSelector Common Pitfalls
Illustrate a common pitfall, like overly broad selectors causing unnecessary recalculations, and then show how to refactor it into a more specific and performant selector.
// Define a non-memoized input selector which simply accesses a part of the state.
const selectItems = state => state.items;
// Define a broad memoized selector using createSelector from Reselect.
// It selects all items and filters by category, causing recalculation even if the category hasn't changed.
const selectItemsByCategory = createSelector(
[selectItems, (_, category) => category],
(items, category) => items.filter(item => item.category === category)
);
This is an example of a common pitfall with overly broad selectors that cause unnecessary recalculations when the state changes but the category does not.
// Define a memoized input selector that selects a specific category from the state.
const makeSelectItemsForCategory = () => {
const selectItemsForCategory = createSelector(
[selectItems, (_, category) => category],
(items, category) => items.filter(item => item.category === category)
);
return selectItemsForCategory;
};
This refactored example uses a selector factory to create a specific memoized selector for each category. It avoids unnecessary recalculations across different categories.