Redux principles

Redux follows three basic principles:

  • The whole state of the application is stored in a single immutable state tree called store. No state management is allowed outside the store. A central immutable store has a lot of benefits. You can improve the performance by using ChangeDetectionStrategy.OnPush because with immutable data, Angular only needs to check object references to detect changes. Furthermore, the undo/redo functionality is easy done.
  • Actions are used to send information from the application to the store. Only actions are source of information for the store. Actions are plain JavaScript objects having type and payload properties. The type property describes a kind of state change we want. The payload property is the data being sent to the store in order to update it.
  • State changes are made through pure functions called reducers. Pure functions are functions that don't mutate objects, but return brand new objects instead. We can grasp reducers as processing steps in the store that allow state transitions. The reducer operates on the current state and returns a new state.

In general, the data flow is bi-directional. User inputs in one component can affect other components and vice versa. The data flow in Redux applications is uni-directional. Changes in the view trigger actions. Actions are dispatched to the store. Reducers perform state changes in response to actions by taking the previous state with the dispatched action and returning the next state as a new object.

Object.assign() and the spread operator can help in returning new objects (http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html).

Several components can subscribe to the store to observe state changes over time and propagate them to the view. The following diagram memorizes described Redux principles:

A classic Redux store provides two important APIs to:

  • Dispatch actions using store.dispatch(action)
  • Register listeners for change notification using store.subscribe(callback)

As you see, if you use a Redux store, you don't need to synchronize the state between components manually.

A predictable state management allows to debug applications with co, called time-travelling debugger. You need to install store-devtools (https://github.com/ngrx/store-devtools) with an appropriate Chrome extension.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.192