## React Redux Primer ![React Logo](react-logo.png) ![Redux Logo](redux-logo.png) An primer from the backend engineer perspective.
## Why React + Redux? - React is a library, not a *framework*. It optimizes rendering. - Redux manages the state. - Other usage: react + mobx, react + apollo(graphql)
### Virtual DOM - maintain a virtual DOM for the current state - observe the state change - diff the AST node change - commit the change to the real DOM by `render()` Also makes the testing easier, see enzyme.
### Flux ![Flux flow](flux-simple-f8-diagram-explained-1300w.png)
Challenges
ES6 + JSX
Babel
webpack
.. need polyfill
eslint
jest + enzyme
flow, TypeScript
npm vs yarn
postcss
stylelint
prettier
## React Component [Demo: React Counter](https://codepen.io/kunxi/pen/zJxNry)
## Stateless Functional Component, aka SFC [Demo: React Counter in Stateless Functional Component](https://codepen.io/kunxi/pen/rZayGx) Note: This is **NOT** `PureComponent`
### Recap - The state is managed *outside* the component, `store` - The state is mapped to `props` to render the component, `mapStateToProps`. - The action `incre` modifies the state, `reducer`. - Then the state change is observed to trigger re-render.
## React + Redux [Demo: React Counter with Redux](https://codepen.io/kunxi/pen/YOPxyQ)
## Redux Best Practice - Use constants instead hard-coded `'INCR'` string. - Use `action` functions instead of the `dispatch`. - Be cautious of the `onClick` event. [Demo: Redux Best Practice](https://codepen.io/kunxi/pen/dqPVGj)
## Redux Best Practice: Combined Reducer - Divide and Conquer for more complicated state management. - The action MUST be unique across all reducers, otherwise, the action MAY modify other states. - That also justifies the consolidated `constants`. [Demo: Redux with Combined Reducers](https://codepen.io/kunxi/pen/mGyBYy)
## Redux with Async Action - What if action requires remote API call? - Or delay? Use `redux-thunk` and / or `redux-saga`. [Demo: Redux with Async Action](https://codepen.io/kunxi/pen/gdboMe)