This post is aimed at people who already know React and Redux. This will aid them in better understanding how things work under the hood.
When I first got into the React universe 🌐, ~3 years ago, I had a very hard time understanding how Redux’s
mapDispatchToPropsworked and were available to the React component. Here is a diagrammatic guide to better understand how Redux’s
connectworks with React.
Let’s say we have a
And a classic Redux store.
Let’s populate the Redux store with
Action dispatchers and the
defaultState looks like this. The
action parameter inside the
Reducer function comes from the dispatched
Let’s connect the React search component with the Redux store. The React-Redux library has official React bindings for Redux.
It provides the
connect function to connect the component to the store.
mapDispatchToProps means map the Action’s
dispatch function to React component’s
The same applies to
mapStateToProps , where the Reducer’s state is mapped to React component’s
- Connect React to Redux.
mapDispatchToPropsdeals with the Redux store’s
stateand the Action’s
dispatchare available via
this.propsto the React component.
Let us summarize the entire React to Redux connect workflow via a button click from the React search component.
- Click the
submitbutton on the React search component
clickfunction dispatches an Action. The Action
dispatchfunction is connected to the search component via
mapDispatchToPropsand is made available to
- (out of scope for this post) The dispatched action is responsible to
fetchdata and dispatch another action to update the Reducer state
- The Reducer state updates itself with the new search data available from Step 3.
- The Reducer state is already connected to
this.propsin the search component via
this.propshas the latest search data and the view now re-renders to show the updated search results
Coder, Speaker, Thinker, Writer, Foodie & Traveller