tezvyn:

NgRx Selectors: Memoized Queries for Your State

AI-drafted, machine-checkedSource: ngrx.iointermediate

NgRx selectors are smart, cached queries for your app's state. They use memoization to avoid re-computing derived data if the underlying state hasn't changed. This prevents needless re-renders.

WHY IT EXISTS: In a reactive app, state changes can trigger a cascade of updates. Re-calculating derived data (like a filtered list or a shopping cart total) on every single state change, even unrelated ones, is inefficient and can lead to performance bottlenecks and unnecessary UI re-renders.

THE MENTAL MODEL: An NgRx selector is a memoized query for your state store. Imagine asking a librarian for a list of books by a specific author. A memoized librarian, if asked the same question twice, would just hand you the same list they already prepared, instead of searching the entire library again. Selectors do this for your data, only re-computing when the underlying state they depend on actually changes.

HOW IT WORKS: NgRx's createSelector function takes one or more "input" selectors and a final "projector" function. The projector function computes a new value from the results of the inputs. NgRx memoizes this projector. Before running it, NgRx checks if the values from the input selectors have changed using strict reference equality (===). If they haven't, it returns the previously computed value instantly, skipping the expensive computation.

WHEN TO USE IT: Use selectors whenever you read data from the store, especially for deriving data. Three key places this shows up: first, filtering a list of todos to show only active ones; second, calculating the total price of items in a shopping cart; third, combining user profile and permissions state into a single view model for a component.

WHEN NOT TO USE IT: Avoid creating selectors inside component lifecycle hooks or methods like ngOnInit. This creates a new, non-memoized selector instance on every component initialization, defeating the entire purpose. Define selectors in a central, static location so they are created only once. Also, do not use selectors for performing side effects; that is the job of NgRx Effects.

ONE CANONICAL EXAMPLE: To get a list of active users, you might create a selector. First, an input selector gets all users: selectUsers = (state) => state.users. The final selector takes this input and computes a result: selectActiveUsers = createSelector(selectUsers, (users) => users.filter(u => u.active)). This filter operation only re-runs if the users array reference changes, not on every state update in the application.

Read the original → ngrx.io

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.