I've worked on some Angular 2+ projects and I'm still wondering why we do need NgRX. I could implement everything with services and it seems that they are easier to understand. I'm not sure if this is because I'm not familiar with NgRX, but anyway I couldn't find the certain use case for NgRX. Can anyone give me some explanations regarding the following?
- difference between state implementation by NgRx and Services
- pros and cons of each implementation
- what do we need to consider when implementing the NgRX?
- any concerns with performance?
This will be a rather
ngrx
-pro post since I have been using it for nearly 3 years now. I have seen a lot of times where it went offboard and managing thengrx
-state became a pain but mostly it was due to disregard of application architecture and best pratices. When applied right it is a pleasure to write and reviewngrx
code because things have a strict structure.IMHO: It can be used in any application, it really makes sense in bigger ones. All that
ngrx
can do for you can also be built using services but on the long run that will get harder and harder. By the time you realize you needed it, it will be too late.Here is an article discussing it all.
https://blog.strongbrew.io/do-we-really-need-redux/
While
ngrx
is pretty opinionted about how to read/update/write data, services leave much more up to the developer. I tend to prefer CRUD operations to be opitinionated for consistency.Observables
which hold data and functions to update data in saidObservables
. Often this means that we end up re-creating CRUD operations in each of these services.ngrx
exposes data asselectors
and update/delete functions asactions
. On top of that there areeffects
to deal with async operations. There is a clear distinction between reading and writing as the logic happens in differnt places as opposed to Service classes which do all-in-one mostly.There are a few things which make
ngrx
valuable, e.g. its extensions but they need to be used and configured right. The main value for me is the consistency it gives.@ngrx/entity
-package which makes managing collections much easier because it provides methods such asupsertOne
orupdateMany
which have clearly-defined types. It also provides easy access by generating selectors:@ngrx/data
is an extension of@ngrx/entity
package takes away writing a lot of services by providing API methods to update/delete... entities@ngrx/effects
using your own services.Performance can be affected if
@ngrx
best practices are disregarded:ngrx
selectors which were created withcreateSelector
are memoized, which means that they will only ever trigger changes when the state changes. This is a performance-pro forngrx
, to re-implement this in a sea of services can be a lot of workGet your best practices right as soon as possible.