Redux-Step-By-Step

Stephen Cui ... 2019-11-07 00:21:50
  • Redux
  • React-Redux
  • Redux Middleware
  • Redux-Pack
  • Redux-Thunk
About 2 min

# Introduce Redux

Redux is a implement of thought of Flux[^1], and it is called predictable state container for JavaScript Apps.

Please download Demo Project (opens new window) and checkout to certain commit.

# 0. Mind Graph

# 1. What is the difference between FBFlux, Redux, Reflux and Alt

FBFlux: original Flux implementation, not support async action. Reflux: the older Flux implementation, not good at log support Alt: like Reflux, better syntax then Flux Redux: Newest one. Three principles: single source of truth, state is read-only and changes are made with pure functions. More Reading (opens new window)

# 2. if use Redux only

Run command yarn add redux

Action:

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

export function increment() {
  return { type: INCREMENT };
}

export function decrement() {
  return { type: DECREMENT };
}
1
2
3
4
5
6
7
8
9
10

Reducers:

function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}
1
2
3
4
5
6
7
8
9
10

View/Component:

export class ReduxStandalone extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      counter: 0
    };

    store.subscribe(() => {
      this.setState({
        counter: store.getState().pure
      });
    });
  }

  render() {
    return (
      <>
        <p>Only Redux Package</p>
        <button onClick={() => this.handleIncrementEvent()}>Add</button>
        <button onClick={() => this.handleDeIncrementEvent()}>Minus</button>
        <label>Counter: {this.state.counter}</label>
      </>
    );
  }

  handleIncrementEvent = () => {
    store.dispatch(increment());
  };

  handleDeIncrementEvent = () => {
    store.dispatch(decrement());
  };
}

export default ReduxStandalone;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

As we create plain object Action and Reducer and then use Store into Component. Trigger action on Button And bind store dispatch event into current state.

Note: Please checkout commit b58bf4e6 for more detail.

# 3. How to use React Redux

Run command yarn add react-redux

Action:

export const addTodoAction = number => ({
  type: ADD_TODO_ACTION_TYPE,
  number: number + 1
});
1
2
3
4

Component:

const ToDo = ({ addTodoAction, todos }) => {
  return (
    <>
      <button onClick={() => addTodoAction((todos || []).length)}>Add Todo</button>
      <p>My ToDo List</p>
      <ul>
        {todos.map(t => {
          return <li key={t}>{t}</li>;
        })}
      </ul>
    </>
  );
};

const mapStateToProps = state => ({
  todos: state.basic.todos
});

const mapDispatchToProps = {
  addTodoAction
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ToDo);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

In this section we use react-redux library to get more ability with api of connect, Provider, combineReducers. But if I have to get data from api call, how to solve this problem?

Note: Please checkout commit 90a1eef1 for more detail.

# 4. How to solve async action

This time we introduce the concept of Middleware by React Redux. Use this feature we can make our action as a function or Promise based function, and also middleware's ability is more fancy.

# 4.1 Support Promise Async without any third part middleware.

const myThunk = ({ dispatch, getState }) => next => action => {
  /* if the action is an async action */
  if (action && typeof action.then === 'function' /* or user is-promise library */) {
    action.then(action => dispatch(action));
    return;
  }
  return next(action);
};

const store = createStore(RootReducers, applyMiddleware(myThunk));
1
2
3
4
5
6
7
8
9
10

Note: Please checkout commit 2f6221bb for more detail.

# 5. More Middlewares

# Reference

Flux (opens new window) FB Flux (opens new window) reflux (opens new window) Flux Implement Comparation (opens new window)

# Question

What is Elm architecture?

What is difference between Flux and MVC?

What is FBFlux?

What is Reflux?

What is the main point between these flux implements? https://redux.js.org/introduction/prior-art

Last update: October 10, 2021 09:12
Contributors: Stephen Cui