This is a study note about Ngrx store and effects.
A SPA application may have several types of state: server response data, user information (login status, token etc), user input, UI state, and router/location state. Ngrx uses a store to manage all states of an application. State management means modeling state, updating state, read state values, monitor/observe state changes.
Ngrx is baded on Redux that are based on three principles:
- single source of truth: a single store for all state values. This makes the app more predictable, maintainable, and testable.
- state is read-only: immutable update patterns where changes are done via action dispatching.
- pure functions update state: pure functions (reducers) respond to action types and return new state.
ngrx/store is a redux inspired reactive state management made for Angular. It is immutable thus allows
ChangeDetectionStrategy.OnPush for quick change detection. It supports lazy-loaded modules.
Components can be in two groups: container that is aware of store, dispatch actions and read data from store; a presentational component is not aware of store, invokes callbacks via
@Output and read data from
@Input. A container selects data from a store and dispatches actions to a store. A store is a reactive data source.
ngrx/effects provides a side effects model for Ngrx/store. It listens for store actions (before the reducers get the actions) and performs functions outside the store and outside Angular. It dispatchs actions when it gets results from outside services. Ngrx uses observables in service apis. If both a reducer and an effect listen to the same action, the reducer is executed first.
Only reducers change the state using immutable data structure.