Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

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.

selectors.jsJavaScript
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);
Text
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.

Also inFunctions
Taggedredux
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.