I have an anuglar2 project that communicates with an api. Recently, I decided to integrate ngrx/store to maintain the state of the components, and follow the dump-smart component architecture. But then while moving on, I read about ngrx/effect which can be used upon the api requests.
And here my question comes, why should I use the ngrx/effect library, over just calling the corresponding function in my service from my container component to perform the api request and on success dispatch action to save the returned values in my store.
NgRx Effects are a popular part of NgRx, a state management library built for Angular. Effects are usually used to perform side effects like fetching data using HTTP, WebSockets, writing to browser storage, and more.
NgRx is a popular solution in the Angular ecosystem if you are building complex web applications with sophisticated state management. Characteristics of the need for NgRx are many user interactions and multiple data sources. NgRx is a good choice, if: the state should be accessed by many components and services.
Luckily, NgRx provides state and action sanitizers that can be used to clean up your data to reduce the amount of state (for example, multiple arrays with thousands of items) to improve the performance of the devtool.
NgRx, which is the Angular version of Redux for React is for State Management. In React, state management can get complicated, and Redux is there to help. For Angular, this should not be the case as everything is synced due to two way data binding.
If your case stays that simple, then you won't need an effect
for it. Besides, the effect
itself will do not much more than calling your service-method.
In short: If you project is very small and without many features, it will just cause you to write more code.
If you project is large, it will help you structure your data-flows and project-components.
When you want to trigger an action based on another action(in spoken english you would call this a side-effect
) or when you want to add a generic error-handling or maybe a logging.
The way an effect
works: The effect
listens for any defined action(s) (e.g. LoadDataAction), then does some processing and returns any action(s) that are then processed by the store and distributed to a reducer or some other effect
.
Example:
effect
(loadData$) is triggeredeffect
calls the data-serviceeffect
return a LoadDataFailureAction
ngrx processes the action...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With