What is Selector in NgRx: Explanation and Example
selector is a pure function that extracts and returns specific pieces of state from the store. It helps you get only the data you need in a simple and efficient way, improving performance and code clarity.How It Works
Think of the NgRx store as a big filing cabinet holding all your app's data. A selector is like a special label that helps you quickly find and pull out just the papers you need without opening every drawer.
Selectors are pure functions that take the whole state and return a smaller part of it. They can also combine or transform data before giving it back. This makes your app faster because it only updates components when the specific data they use changes.
Using selectors is like having a smart assistant who remembers exactly where each piece of information is and only brings you what you ask for, keeping your app organized and efficient.
Example
This example shows how to create a selector to get the list of users from the state.
import { createSelector, createFeatureSelector } from '@ngrx/store'; interface User { id: number; name: string; } interface AppState { users: User[]; } // Step 1: Select the 'users' slice from the state const selectUsersFeature = createFeatureSelector<User[]>('users'); // Step 2: Create a selector to get all users export const selectAllUsers = createSelector( selectUsersFeature, (users) => users ); // Usage example (in a component): // this.store.select(selectAllUsers).subscribe(users => console.log(users));
When to Use
Use selectors whenever you need to read data from the NgRx store in your Angular app. They are especially helpful when you want to:
- Get specific parts of the state without exposing the whole store.
- Reuse data queries in multiple components.
- Optimize performance by preventing unnecessary component updates.
- Combine or transform state data before using it.
For example, if you have a list of products and want to show only those in stock, a selector can filter and return just those products efficiently.
Key Points
- Selectors are pure functions that read and return parts of the store state.
- They improve app performance by memoizing results and avoiding unnecessary updates.
- Selectors can be composed to build complex data queries.
- Use
createSelectorandcreateFeatureSelectorto define selectors in NgRx.