Blog>
Snippets

Memoizing Selectors for Performance

Provide an example of creating a memoized selector function to calculate derived data (e.g., count of completed todos) from the state, showcasing how to prevent unnecessary computations and re-renders.
import { createSelector } from 'reselect';
Import createSelector from reselect library for creating memoized selectors.
const todosSelector = state => state.todos;
Define a basic selector to extract todos from the state.
const completedTodosSelector = createSelector(
  [todosSelector],
  (todos) => todos.filter(todo => todo.completed).length
);
Create a memoized selector for counting completed todos. It only recomputes the count if the list of todos changes.
const mapStateToProps = (state) => ({
  completedTodosCount: completedTodosSelector(state)
});
Map the state to props using the memoized selector to provide the count of completed todos to a component.