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
- Single Source of Truth: one app - one store - one state (Components are free to contain internal state)
- 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.
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 | { |
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.
- The event handler function dispatches an action to the store, with
store.dispatch()
. - Redux passes the dispatched action to the reducer.
- The store saves the new state returned by the reducer.
- Since we subscribe the store, the function we provided will be called and update the UI.