Selectors

Selectors are pure functions used for obtaining slices of store state. @ngrx/store provides a few helper functions for optimizing this selection. Selectors provide many features when selecting slices of state:

  • Portability

  • Memoization

  • Composition

  • Testability

  • Type Safety

When using the createSelector and createFeatureSelector functions @ngrx/store keeps track of the latest arguments in which your selector function was invoked. Because selectors are pure functions, the last result can be returned when the arguments match without reinvoking your selector function. This can provide performance benefits, particularly with selectors that perform expensive computation. This practice is known as memoization.

Selectors are pure functions that take slices of state as arguments and return some state data that we can pass to our components. To better understand what selectors are and what they do, it helps see ngrx state as a data structure - a tree that can be serialised to JSON. Data is added to the state tree by composing state in reducers - that’s the easy part. Now to get data out of the state tree, we have to traverse it to find our property of interest - and return it. That can become more complex, and is where selectors help us out.

You may have already seen the store.select method being used to get data from the store by passing it a string value:

this.store.select('pizzas');

The string represents the name of a slice of state in the store and we can expect this function to return data corresponding to our pizzas property - perhaps an array of pizzas. However, store.select can also take a function instead, which takes a slice of state and returns a property from the state (which you’ve likely already seen as well):

this.store.select(state => state.pizzas);

Last updated