State Management: Selector

We know how to create a State and dispatch actions to update its value. Now let’s see how to receive updates when the State gets updated.

Most state management libraries provide what is known as Selectors. A Selector query function runs against our State and returns an Observable. For instance, with NgXs, a Selector can be created with the @Select decorator as follows:

The above code creates an Observable that returns any value update in state.currencyInfo. If you don’t like decorators, you can also use the select function from the Store service:

Both options return a similar Observable. If a Selector of a slice of your State is used repeatedly, you can make it a memoized selector by using the @Selector decorator in your State class. This example creates a new selector that returns just the currency property of our State:

Such a Selector can be used with @Select decorator in your components/services as follows:

You can see that code in action on Stackblitz.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.