Tutorial hero
Lesson icon

NgRx Component Store

Originally published October 06, 2022 Time 2 mins

I’ve been working a lot with @ngrx/component-store again this week, and it has made me want to highlight how good of an option it is not just for local component state, but also as a simple approach to global state management.

If you are already using the service with a subject approach to manage state, then it is reasonably straightforward to refactor that into a service that uses Component Store for state instead.

I won’t dive into too much detail here, but suppose you have a service that looks something like this:

service that uses Component Store for state

This is fine - but there is some slight awkwardness to it. In this particular case, we have to manually manage the private/public subjects for exposing data to the application, and the load method also requires a manual subscribe.

We can refactor this to be a little more robust and reactive by using Component Store and the methods it provides us:

refactor and reactive by using Component Store

Using Component Store allows us to define the state we want to track through an interface, and then we can read and update that state using the methods it provides like select, effect, and updater.

We don’t need to manually create private subjects and public observables with this approach, and another notable thing is that with an effect we no longer have to have a manual subscription - Component Store handles the subscription for us.

Of course, there are some concepts you need to learn here first. But, as far as state management solutions go, there is relatively little that you will need to get up to speed with and the documentation is great.

Learn to build modern Angular apps with my course