Blog>
Snippets

Basic Selector Creation with createSelector

Demonstrate how to use createSelector to compute a simple derived state, such as filtering a list of products by category.
import { createSelector } from 'reselect';

// Input selector: gets the products array from state
const selectProducts = state => state.products;

// Input selector: gets the current category filter
const selectCurrentCategory = state => state.currentCategory;

// Output selector: derives the filtered products list based on the category
const selectProductsByCategory = createSelector(
    [selectProducts, selectCurrentCategory],
    (products, category) => products.filter(product => product.category === category)
);

// To use the selector:
// `state` would be the Redux store state
// const filteredProducts = selectProductsByCategory(state);
This example demonstrates the use of createSelector from the Reselect library to derive a filtered list of products by category. Two input selectors are used to retrieve the products array and the current category from the state. An output selector is created to compute the filtered list, which only includes products matching the current category.