tezvyn:

Memoized Selectors: Avoid Needless Re-renders

AI-drafted, machine-checkedSource: reselect.js.orgadvanced

A memoized selector caches its result, re-running only if its inputs from the Redux store change. Use it to compute derived data like a filtered list without triggering needless re-renders.

WHY IT EXISTS: In a Redux application, any state change notifies all connected components. If a component calculates derived data (like filtering a list) directly, it will re-calculate on every single state update, even unrelated ones. This is inefficient and causes unnecessary component re-renders.

THE MENTAL MODEL: A memoized selector is like a gatekeeper for derived data. It takes small, specific slices of the Redux state as inputs. It runs a calculation once and caches the result. On subsequent calls, it first checks if its inputs have changed. If not, it returns the cached result instantly. Crucially, it returns the exact same object reference, which React's shallow comparison (===) sees as unchanged, preventing a re-render.

HOW IT WORKS: Libraries like Reselect provide a createSelector function. You give it one or more "input selectors" (simple functions that extract pieces of state) and a "result function" that performs the computation. This creates a new, memoized selector. When this new selector is called with the global state, it runs the input selectors, compares their results to the previous call, and only executes the result function if an input has changed.

WHEN TO USE IT: Use memoized selectors whenever you compute derived data from the Redux state that will be used in a component. This is ideal for filtering a list of items, aggregating data like a shopping cart total, or transforming data into a specific shape for the UI. It prevents expensive computations and unnecessary re-renders.

WHEN NOT TO USE IT: Avoid selectors for simple state lookups that involve no computation (e.g., state => state.user.name), as the overhead is not justified. Also, if the input data is guaranteed to change on every render anyway, a selector provides no benefit as its cache would be constantly invalidated.

ONE CANONICAL EXAMPLE: In a todo app, you have a list of todos and a visibility filter. A selector can take state.todos and state.visibilityFilter as inputs and return the filtered list. If you mark a todo complete, the state.todos input changes, the selector re-runs, and the component gets a new list. But if some unrelated state changes (like a loading status), the selector's inputs remain the same, it returns the cached list, and the component avoids a pointless re-render.

Read the original → reselect.js.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.