Avoiding Selector Recomputations with Non-Primitive Arguments
Use createSelector to correctly memoize selectors when dealing with non-primitive arguments, preventing unnecessary recomputations.
import { createSelector } from 'reselect';
// A state selector to get categories map
const selectCategoriesMap = state => state.categoriesMap;
// A selector to get items by category ID
const makeSelectItemsByCategoryId = () => createSelector(
[selectCategoriesMap],
(categoriesMap) => categoryId => categoriesMap[categoryId] || []
);
Creates a memoized selector factory function to select items by category ID. It takes advantage of closure to keep the categoryId parameter stable, preventing unnecessary recomputations when passing non-primitive arguments.
const selectItemsByCategoryId = makeSelectItemsByCategoryId();
// Later in your code, such as in mapStateToProps or a useSelector hook
const mapStateToProps = (state, ownProps) => ({
items: selectItemsByCategoryId(state)(ownProps.categoryId)
});
Utilizes the previously created selector factory and provides a stable reference to the categoryId, allowing for correct memoization and avoiding recomputations when the categoryId remains the same.