State Management: ngrx/store vs Angular services

State management is one of the most difficult tasks in front-end development. In Angular2 we are presented with a number of options. The most promising ones seem to be holding reusable state in services vs. using the ngrx/store library specifically designed to help with state management. Here are my current views on the pros and cons of each approach.

Pros of using ngrx/store

  • You always know where all your state is
  • Everything is an observable => more flexibility to use stores
  • You get dev tools such as time-travel
  • It could become a standard
  • There are some examples

Cons of using ngrx/store

  • The examples don’t cover real world cases like having an actual database with items with ids.
  • Everything is an observable => more complexity in use
  • It could become an outdated library
  • Difficulty to learn
  • Name-spacing is ugly, e.g. '[heroes] UPDATE'.
  • Idea of immutability is nice but from the example //remember to avoid mutation within reducers. Having to remember is not so nice. It makes the reducers fragile and it’s easy to introduce sneaky bugs since nothing guarantees the immutability.

Pros of using services as your store

  • No extra library needed, it’s core Angular
  • Complete flexibility in use
  • You can have stores that aren’t observables
  • You can throw immutability overboard
  • No name-spacing problems as every resource has it’s own service

Cons of using services as your store

  • No-one tells you how to do it, no standards

Conclusion

I still prefer the manual approach with services. I think it adds a lot to the flexibility and simplicity that you can shape your data-store as you need it. Often you don’t need the entire store store to be an observable and you can easily extend your store-services to make them observables once you need that feature. For example I’d rather have a store with the signature

heroStore: {[heroId: string]: BehaviorSubject<Hero>}

than the signature

heroStore: BehaviorSubject<{[heroId: string]: Hero}>

As long as I don’t need something like the total number of heroes it’s completely sufficient to have the first signature. And in case I suddenly need the store as an observable in my app, I can still easily change the service.

Also the mistakes in the docs and an example-app that’s far from real-world scare me a bit. For me this shows too little dev power in a project too big to stem and a concept that’s not guaranteed to be ideal. I mean it’s an interesting idea to combine the principles of redux with observables, but maybe it’s a little overkill?

Leave a Reply

Your email address will not be published.