prawin-s / LEARNings

0 stars 0 forks source link

State management with NgRx : 3 Short Principles #1

Open prawin-s opened 3 years ago

prawin-s commented 3 years ago

Following three short principles are the foundation for state management with NgRx:

Single Source of Truth: The application state is stored in one object

State is Read-Only: You cannot change the current state, only dispatch an action and produce a new state.

Changes are made with pure functions: The next state is produced purely based on the current state and a dispatched action - no side-effects allowed

Together these principles make sure that state transitions are explicit and deterministic, meaning you can easily tell how the application state evolves over time.

Action, State & Reducer :

Action Actions are plain JavaScript objects that reference events occurring in the application. Actions are distinguished by a type but can have arbitrary more properties to serve as a payload containing information about a corresponding event.

State A plain JavaScript object holds the global application state.

Reducer A reducer is a pure function that takes the current state and an action as parameters while returning the next state.

Where Does NgRx Store Data? NgRx stores the application state in an RxJS observable inside an Angular service called Store. At the same time, this service implements the Observable interface. So, when you subscribe to the store, the service actually forwards the subscription to the underlying observable.

Internally, NgRx is actually using a BehaviorSubject which is a special observable that has the following characteristics:

How NgRx Effects Works? NgRx effects are managing asynchronous side-effects with RxJS observables resulting in actions being dispatched to the store. Since reducers are pure functions, they can't have side-effects - so things like HTTP requests aren't allowed. However, actions can be dispatched at anytime, for example as the result of an HTTP request that saves a data to the server.

prawin-s commented 3 years ago

Link : https://dev.to/angular/how-ngrx-store-effects-work-20-loc-re-implementation-2i41