Connect React to Redux - a diagrammatic guide

This post is aimed at people already knowing React, Redux and aids 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 mapStateToProps and mapDispatchToProps worked and were available to the React component. Here is a diagrammatic guide to better understand how Redux’s connect works with React.

Let’s say we have a Search component.

The React component

And a classic Redux store.

The Redux store

Let’s populate the Redux store with Action dispatchers and the Reducer state.

Redux store with Action dispatchers and the Reducer state

The Reducer’s defaultState looks like this 👇. The action parameter inside the Reducer function comes from the dispatchedAction.

Reducer’s defaultState

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 this.props .

The same applies to mapStateToProps , where the Reducer’s state is mapped to React component’s this.props .

Connect React component to the Redux store
  1. Connect React to Redux.
  2. The mapStateToProps and mapDispatchToProps deals with the Redux store’s state and dispatch, respectively.
  3. Reducer’s state and the Action’s dispatch are available via this.props to the React component.
React to Redux connect flow 

Let us summarise the entire React to Redux connect workflow via a button click from the React search component.

React to Redux connect flow via button click
  1. Click the submit button on the React search component
  2. The click function dispatches an Action . The Action dispatch function is connected to the search component via mapDispatchToProps and is made available to this.props
  3. (out of scope for this post) The dispatched action is responsible to fetch data and dispatch another action to update the Reducer state
  4. The Reducer state updates itself with the new search data available from Step 3.
  5. The Reducer state is already connected to this.props in the search component via mapStateToProps
  6. this.props has the latest search data and the view now re-renders to show the updated search results
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: