Blog>
Snippets

Reselect Selector for Expense Filtering

Implement a Reselect selector that computes and memoizes a list of expenses filtered by a specific category, avoiding unnecessary re-renders.
import { createSelector } from 'reselect';

// Define input-selector to get the expenses array from the state
const getExpenses = state => state.expenses;

// Define input-selector to get the current filtering category from the state
const getCategoryFilter = state => state.filterCategory;

// Create a memoized selector that derives the filtered expenses
const getFilteredExpenses = createSelector(
  [getExpenses, getCategoryFilter],
  (expenses, category) => expenses.filter(expense => expense.category === category)
);

export { getFilteredExpenses };
This code first imports the createSelector function from the reselect library. Two input-selectors are defined: getExpenses and getCategoryFilter which extract the expenses array and the category to filter by from the Redux state. Then, it creates a memoized selector, getFilteredExpenses, that computes the filtered list of expenses when either the expenses array or the category filter changes. The filtered expenses array is returned only if the inputs have changed, otherwise, a cached result is returned, preventing unnecessary re-renders.