Memoize selectors in state management
Memoize a derived-data selector with Reselect createSelector so it recalculates only when its inputs change, and returns the same array reference otherwise.
A selector that filters or sorts state returns a new array every time it runs, so components that use it re-render even though nothing changed. A memoized selector returns the previous result while its inputs are unchanged.
import { createSelector } from 'reselect';
const selectTodos = (state) => state.todos;
const selectFilter = (state) => state.filter;
export const selectVisible = createSelector([selectTodos, selectFilter], (todos, filter) => {
console.log('recomputing');
return todos.filter((todo) => todo.status === filter);
});
const state = { todos: [{ id: 1, status: 'open' }, { id: 2, status: 'done' }], filter: 'open' };
const first = selectVisible(state);
const second = selectVisible(state);
console.log(first === second, first);recomputing
true [ { id: 1, status: 'open' } ]The calculation ran once, and the second call returned the identical array, so first === second is true. Reselect compares each input selector's result by reference, and recalculates only when one of them changed.
This only works when the state is updated immutably, so a changed list is a new array. A selector that takes extra arguments, such as an id, needs a separate memoized instance for each, because Reselect remembers one set of arguments by default. For cheap derivations, such as reading a field, memoization costs more than it saves. See Reselect.