Notes

General React-Redux Flow

Edit on GitHub

Redux
2 minutes

General React-Redux Flow

  1. Create actions and reducers
  2. Connect the app to store with Provider
  3. Create a container
  • mapStateToProps
  • mapDispatchToProps
  • connect
  1. Using state and dispatch

connecting the store

1import { Provider } from 'react-redux
2
3ReactDOM.render(
4  <Provider store={store}>
5    <MyRootComponent />
6  </Provider>,
7  document.getElementById('root')
8)

Creating a container

1import React from 'react
2import { connect } from 'react-redux'
3
4class MyClass extends React.Component {}
5
6function mapStateToProps (state, ownProps) {}
7function mapDispatchToProps (state, ownProps) {}
8
9export default connect(mapStateToProps, mapDispatchToProps)(MyClass)

You can pass down the whole state to the connect function, or you can map your props and actions and then connect them, it’s up to you really. Mapping it does make it more presentable and easier to maintain, but might not be that helpful if only have fancy little in state.

1export default connect(state => state)(MyClass)

Using Redux State and Dispatching Redux Actions from React Containers

Once you have mapped your redux state and dispatch with mapStateToProps and mapDispatchToProps, you can now use the state and dispatch actions in React conatiner components.

The redux state is passed as a prop to your connected React container components, and you can access redux stuff with this.props

1// Dispatching actions
2this.props.dispatch(myAction()) // ignored mapDispatchToProps, calling directly from state
3this.props.myAction() // manually wrapped action in mapDispatchToProps
4this.props.actions.myAction() // used bindActionCreators in mapDispatchToProps
5
6// Using state
7this.props.state.blah // ignored mapStateToProps, calling directly
8this.props.blah // calling specific state parts mapped in mapStateToProps