REDUX

Notes for MEDIUM

Terminology

  • Application state - A global object which holds info for various purposes in the app (e.g. A loading indicator should be stored as a boolean field to decide whether to be displayed)
  • Serializable data - The only thing should be stored in Redux
  • Two patterns Redux follows
    1. Single Source of Truth: one app - one store - one state (Components are free to contain internal state)
    2. Immutability: The state object will not be directly changed. We need to create a new object, recalculate the app state and update it with the newly-created object, and leave the old state intact.

REDUX DATA FLOW

  • Three main parts in Redux
    1. Actions
    2. Reducers
    3. Store

      Store

Store is an object, not a class. To follow the pattern, only one store needed to be created.

Store is a “state tree“, put whatever data needed to the store and nest them.

Actions

Describe what happened.

The actions will be dispatch (send) to the store, whenever the state needed to be updated.

Actions need to contain a type field, to describe what kind of action we are dispatching.

1
2
3
4
5
{
type: ADD_NOTE,
title: 'some title', // optional
content: 'Hi content', // optional
}

Action creator will generate dynamic actions as a function which returns an object.

Reducer

functions that define HOW the state changes.

The action will be passed to the reducer, a reducer function takes two parameters previousState and action.

Reducer will calculate the new state of the app.

In a real-world app, we separate reducers into multiple simpler one, and combine them with a helper function called combineReducers.

Data flow

If user triggers an event, clicks a button for example.

  1. The event handler function dispatches an action to the store, with store.dispatch().
  2. Redux passes the dispatched action to the reducer.
  3. The store saves the new state returned by the reducer.
  4. Since we subscribe the store, the function we provided will be called and update the UI.