Angular State Management with NgRx

This guide aims on understanding why you may need local or global state management as well as get you started with NgRx which is a library that brings Redux-like reactive state management to Angular.

Getting Started

1 .Why use NgRx

One of the biggest challenges with any application is managing data. In angular there are many patterns we can follow to manage your application data, and most of the time these will involve using the Input or Output decorators to share objects between components (which i know can be painfull if your application handles a lot of data) or things like RxJs Observables to listen to data changes. Now NgRx solves this problem in a reactive, elegant way and also gives you amazing debugging features.

A quick guide line that might help you decide If you do need NgRx Store is the SHARI principle:

  • Shared: state that is accessed by many components and services.

  • Hydrated: state that is persisted and rehydrated from external storage.

  • Available: state that needs to be available when re-entering routes.

  • Retrieved: state that must be retrieved with a side-effect.

  • Impacted: state that is impacted by actions from other sources.

2. How it works

Let’s look at the high level principles of NgRx: Let’s say we have a user interface that is displaying some data, then the user performs some action that shall change the state of that data, in redux the only way to change the state of the data is by dispatching an action, once an action has been dispatched it goes through a reducer function which will copy the current state of the object along with any data changes into a new object, because the state is immutable meaning it can’t be changed directly it has to be copied over to a new state, after the reducer has created the new state it gets saved in a data store which can be thought as a client side database, then in NgRx we treat this store as an observable where we can subscribe to it from anywhere in our application this means that all if our components and services will be sharing the same data at any given point and time, the reason for this is it gives us a predictable tree of state changes which will later come in handy when we want to debug or test our application.

Key NgRx Concepts
  • Actions describe unique events that are dispatched from components and services.

  • State changes are handled by pure functions called reducers that take the current state and the latest action to compute a new state.

  • Selectors are pure functions used to select, derive and compose pieces of state.