Mind is Software

Ying’s thoughts about software and business

Ngrx Store and Effects

This is a study note about Ngrx store and effects.

1 Introduction

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.

There are five core concepts: single state tree, actions, reducers, store, and one-way dataflow. A single state tree is a plain JavaScript object composed by reducers. An action has two properties: a type string and an optional payload data. Actions are dispatched to reducers. A reducer is a pure function that processes actions and returns a new state. A store is a state container. Angular components subscribe to slices of state and dispatch actions to the store. The store invokes reducers with previous state and action. The one-way dataflow means that a component dispatchs an action, an action is sent to a reducer, a reducer generates a new state, the new state is rendered to subscribed components.

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.


Share