Simple createSelector Usage
Show how to create a memoized selector to compute derived data from the state, focusing on reducing redundant calculations.
import { createSelector } from 'reselect';
// Example state for demonstration
const state = {
products: [
{ id: 1, category: 'electronics', name: 'Laptop' },
{ id: 2, category: 'clothing', name: 'T-shirt' },
{ id: 3, category: 'electronics', name: 'Camera' }
],
filterCategory: 'electronics'
};
// Input selector: gets products from state
const getProducts = state => state.products;
// Input selector: gets current filter category from state
const getFilterCategory = state => state.filterCategory;
// Memoized selector: filters products by the selected category
const getFilteredProducts = createSelector(
[getProducts, getFilterCategory],
(products, category) => products.filter(product => product.category === category)
);
// Usage example
const filteredProducts = getFilteredProducts(state); // Returns filtered products
console.log(filteredProducts);
This code demonstrates a simple usage of the 'createSelector' function from the 'reselect' library to create a memoized selector. The selector 'getFilteredProducts' computes the derived state of filtered products based on the products list and a filter category from the Redux state. It only recalculates the result when the inputs (products list or filter category) have changed, thus reducing unnecessary recalculations and optimizing performance.