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?
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 the ngrx
-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 review ngrx
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/
difference between state implementation by NgRx and Services
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 said Observables
. Often this means that we end up re-creating CRUD operations in each of these services.ngrx
exposes data as selectors
and update/delete functions as actions
. On top of that there are effects
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.pros and cons of each implementation
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 as upsertOne
or updateMany
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.any concerns with performance?
Performance can be affected if @ngrx
best practices are disregarded:
ngrx
selectors which were created with createSelector
are memoized, which means that they will only ever trigger changes when the state changes. This is a performance-pro for ngrx
, to re-implement this in a sea of services can be a lot of work
what do we need to consider when implementing the NgRX?
Get your best practices right as soon as possible.