Photo by Austin Neill on Unsplash

State Management in Angular

There’s a new state management option for Angular, called NGXS. Having just completed a large Angular project, with complex state management requirements, I was interested to find out more about it.

A demo app has been provided to show how NGRX and NGXS compare. The way the NGRX code is presented in the demo app does not reflect how I had been working with NGRX, so I wanted to address this. I use the unionize library along side NGRX for “Boilerplate-free functional sum types in TypeScript”. I have extended the “ngxs vs ngrx” demo app to include a third example that shows the ngrx with unionize option. I’ve forked the repo on GitHub here.

I haven’t used NGXS yet, but it does seem to address some of the concerns with NGRX. The main one being that because NGRX is inspired by Redux from the React eco-system, it doesn’t feel very Angular. On first inspection, NGXS does look more like idomatic Angular.

One thing I learned from recent projects, is that most of the time you don’t need to make the jump to a full-on Redux style state management library. You can achieve something simple in Angular, and still get separation of concerns, and modularity using the BehaviourSubject in an injectable service approach. There is a big jump from the simple Angular component style, to a full redux style architecture. Perhaps NGXS could offer an easier transition, because it will be more familiar to Angular developers?

I have found the centralised dispatch of NGRX actions, along with meta-reducers, to be very useful when refactoring, or implementing features that would otherwise require many changes across the whole codebase, or touching many components. Analytics, logging and debugging are just a few examples. It looks like NGXS will have similar benefits, as it has the concept of “plugins”.

In conclusion, I’m going to take a much deeper look at NGXS, as I think it looks promising. From my recent experiences with Angular, on fairly large projects, I gained a good understanding of NGRX and RxJs. This includes where it makes sense to use redux, and where other more idomatic Angular options would be the simpler. It looks like a lot of thought has gone into NGXS, and how to re-imagine the Flux/Redux pattern to better fit with the Angular framework. I’ll be watching how this develops…