3. Motivation
As the requirements for JavaScript SPA have become increasingly complicated, our code must
manage more state than ever before.
Since a model can update another model, then a view can update a model and so on, at some point
you no longer understand what happens in your app.
4. Flux
Flux is the application architecture that Facebook uses for building client-side web applications.
It's more of a pattern rather than a formal framework, and you can start using Flux immediately
without a lot of new code.
Basically, it makes state changes in apps more predictable.
8. Redux
Redux solves the same problems as Flux, plus some.
Redux introduce the reducer function. (state, action) => newState
9. Redux Three Principals
Redux can be described in three fundamental principles:
1. Single source of truth- The state of your whole application is stored in an object tree within a single store.
2. State is read-only- The only way to mutuate the state is to emit an action, an object describing what
happened.
3. Changes are made with pure functions- To specify how the state tree is transformed by actions, you write
pure reducers.
10. Action & Action Creators
As we said, actions are just object describing what happened.
const ADD_TODO = ‘ADD_TODO’;
{
type: ADD_TODO,
text: ‘Hello 8200!’
}
11. Action & Action Creators
Action creators are just functions creating actions.
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
12. Reducer
The job of the reducer is specify how the application’s state changes after the action happened.
Reducer is a function with the following parameters: state, action. State is the current state of the application, action is
describing what happened.
function todos(state = [], action) {
switch(action.type) {
case ADD_TODO:
return [
…state,
{
text: action.text
}
]
}
}
13. Store
The store object is what brings everything together! The store has the following responsibilities:
Holds application state.
Allows access to state via getState().
Allows state to be updated via dispatch(action).
Registers listeners via subscribe(listener).
Handles unregistering of listeners via the function returned by subscribe(listener).
14. Store
We will have a single store in Redux application!
let store = createStore(reducer);
let unsubscribe = store.subscribe(() => console.log(store.getState()));
store.dispatch(action1);
store.dispatch(action2);
unsubcribe();