Advertisement
  1. Code
  2. Web Development

Getting Started With Redux: Connecting Redux With React

Scroll to top
Read Time: 12 min

This is the third part of the series on Getting Started With Redux, and in this tutorial, we're going to learn how to connect a Redux store with React. Redux is an independent library that works with all the popular front-end libraries and frameworks. And it works flawlessly with React because of its functional approach.

You don't need to have followed the previous parts of this series for this tutorial to make sense. If you're here to learn about using React with Redux, you can take the Quick Recap below and then check out the code from the previous part and start from there.

Quick Recap

In the first post, we learned about the Redux workflow and answered the question, Why Redux? We created a very basic demo application and showed you how the various components of Redux—actions, reducers, and the store— are connected.

In the previous post, we started building a contact list application that lets you add contacts and then displays them as a list. We created a Redux store for our contact list, and we added a few reducers and actions. We attempted to dispatch actions and retrieve the new state using store methods like store.dispatch() and store.getState().

By the end of this article, you'll have learned:

  1. the difference between container components and presentational components
  2. about the react-redux library and the redux-js-toolkit
  3. how to bind React and Redux using connect()
  4. how to dispatch actions using mapDispatchToProps
  5. how to retrieve state using mapStateToProps
  6. how to dispatch actions and get the state using the new Redux hooks: useDispatch  and useSelector 

The code for the tutorial is available on GitHub in the react-redux-demo repo. Grab the code from the main branch and use that as a starting point for this tutorial. If you're curious to know how the application looks by the end of this tutorial, try the v2 branch. Let's get started.

Designing a Component Hierarchy: Smart vs. Dumb Components

This is a concept that you've probably heard of before, but let's have a quick look at the difference between smart and dumb components. Recall that we created two separate directories for components, one named containers/ and the other components/. The benefit of this approach is that the behavior logic is separated from the view.

The presentational components are said to be dumb because they are concerned about how things look. They are decoupled from the business logic of the application and receive data and callbacks from a parent component exclusively via props. They don't care if your application is connected to a Redux store if the data is coming from the local state of the parent component.

The container components, on the other hand, deal with the behavioral part and should contain very limited DOM markup and style. They pass the data that needs to be rendered to the dumb components as props.

I've covered the topic in depth in another tutorial, Stateful vs. Stateless Components in React.

Moving on, let's see how we're going to organize our components.

Designing component HierarchyDesigning component HierarchyDesigning component Hierarchy

Presentational Components

Here are the presentational components that we'll be using in this tutorial.

components/AddContactForm.jsx

1
import React from 'react';
2
3
const AddContactForm = ({onInputChange, onFormSubmit}) => 
4
    (
5
		<form>
6
			<div className="form-group">
7
			    <label htmlFor="emailAddress">Email address</label>
8
			    <input type="email" class="form-control" name="email" onChange={onInputChange} placeholder="name@example.com" />
9
			</div>
10
			
11
		{/* Some code omitted for brevity */}
12
			  
13
			<div className="form-group">
14
			    <label htmlFor="physicalAddress">Address</label>
15
			    <textarea className="form-control" name="address" onChange={onInputChange} rows="3"></textarea>
16
			</div>
17
18
			<button type="submit" onClick={onFormSubmit} class="btn btn-primary"> Submit </button>
19
		</form>
20
	)
21
22
export default AddContactForm;

This is an HTML form for adding a new contact. The component receives onInputChange and onFormSubmit callbacks as props. The onInputChange event is triggered when the input value changes and onFormSubmit when the form is being submitted.

components/ContactList.jsx

1
const ContactList = (props) => {
2
    return(	<ul className="list-group" id="contact-list">
3
           		{props.contactList.map(
4
                  (contact) => 
5
                  <li key={contact.email} className="list-group-item"> 
6
                    <ContactCard contact = {contact}/>

7
                  </li>

8
              	)}
9
            </ul>)

10
}
11
12
export default ContactList;

This component receives an array of contact objects as props, hence the name ContactList. We use the Array.map() method to extract individual contact details and then pass on that data to <ContactCard />.

components/ContactCard.jsx

1
const ContactCard = ({contact}) => {
2
    
3
	return(
4
        <div>
5
	        <div className="col-xs-4 col-sm-3">
6
	           {contact.photo !== undefined ?  <img src={contact.photo} alt={contact.name} className="img-fluid rounded-circle" /> :
7
	            						 <img src="img/profile_img.png" alt ={contact.name} className="img-fluid rounded-circle" />}
8
	        </div>
9
	        <div className="col-xs-8 col-sm-9">
10
	            <span className="name">{contact.name + ' ' + contact.surname}</span><br/>
11
	            
12
	            {/* Some code omitted for brevity */}
13
                
14
	        </div>
15
	      </div>
16
        
17
    )
18
}
19
20
export default ContactCard;

This component receives a contact object and displays the contact's name and image. For practical applications, it might make sense to host JavaScript images in the cloud.

Container Components

We're also going to construct bare-bones container components.

containers/Contacts.jsx

1
function Contacts(props) {
2
3
  const returnContactList = () => {
4
    // Retrieve contactlist from the store

5
  }
6
   
7
    return (
8
        <div>   
9
         	<AddContact/>
10
         	<br />
11
          <ContactList contactList={returnContactList()} />

12
        </div>

13
    );
14
  
15
}
16
17
18
export default Contacts;

The returnContactList() function retrieves the array of contact objects and passes it to the ContactList component. Since returnContactList() retrieves the data from the store, we'll leave that logic blank for the moment.

containers/AddContact.jsx

1
function AddContact() {
2
    const shouldAddContactBox = () => {
3
        /* Logic for toggling ContactForm */
4
    }
5
6
    const handleInputChange = (event) => {
7
        const target = event.target;
8
        const value = target.value;
9
    	const name = target.name;
10
11
        /* Logic for handling Input Change */
12
    }
13
14
    const handleSubmit = (e) => {
15
        e.preventDefault()
16
17
        /* Logic for hiding the form and update the state */
18
    }
19
20
    const renderForm = () => {
21
        return(
22
			<div className="col-sm-8 offset-sm-2">
23
				<AddContactForm onFormSubmit={handleSubmit} onInputChange={handleInputChange} />

24
 			</div>

25
 		)
26
    }
27
28
    return(
29
        <div>            
30
            { /* A conditional statement goes here that checks whether the form 

31
                should be displayed or not */}
32
        </div>

33
    )
34
}
35
36
export default AddContact;

We've created three bare-bones handler methods that correspond to the three actions. They all dispatch actions to update the state. We've left out the logic for showing/hiding the form because we need to fetch the state.

Now let's see how to bind React and Redux together.

The react-redux Library

React bindings are not available in Redux by default. You will need to install an extra library called react-redux first.

1
npm install --save react-redux

The library exports many important APIs including a <Provider /> component, a higher-order function known as connect(), and utility hooks like useSelector() and useDispatch().

The Provider Component

Libraries like Redux need to make the store data accessible to the whole React component tree, starting from the root component. The Provider pattern allows the library to pass the data from top to bottom. The code below demonstrates how Provider magically adds the state to all the components in the component tree.

Demo Code

1
import { Provider } from 'react-redux'
2
3
ReactDOM.render(
4
  <Provider store={store}>
5
    <App />
6
  </Provider>,

7
  document.getElementById('root')
8
)

The entire app needs to have access to the store. So we wrap the provider around the app component and then add the data that we need to the tree's context. The descendants of the component then have access to the data.

The connect() Method

Now that we've provided the store to our application, we need to connect React to the store. The only way that you can communicate with the store is by dispatching actions and retrieving the state. We've previously used store.dispatch() to dispatch actions and store.getState() to retrieve the latest snapshot of the state. The connect() method lets you do exactly this, but with the help of two methods known as mapDispatchToProps and mapStateToProps. I have demonstrated this concept in the example below:

Demo Code

1
import {connect} from 'react-redux'
2
3
const AddContact = ({newContact, addContact}) => {
4
  return (
5
    <div>
6
      {newContact.name} <br />
7
      {newContact.email} <br />
8
      {newContact.phone} <br />
9
      
10
      Are you sure you want to add this contact?
11
      <span onClick={addContact}> Yes </span>

12
    </div>

13
  )
14
}
15
16
const mapStateToProps = state => {
17
  return {
18
    newContact : state.contacts.newContact
19
  }
20
}
21
22
const mapDispatchToProps = dispatch => {
23
  return {
24
    addContact : () => dispatch(addContact())
25
  }
26
}
27
28
export default connect(
29
  mapStateToProps,
30
  mapDispatchToProps
31
)(AddContact)

mapStateToProps and mapDispatchToProps both return an object, and the key of this object becomes a prop of the connected component. For instance, state.contacts.newContact is mapped to props.newContact. The action creator addContact() is mapped to props.addContact.

But for this to work, you need the last line in the code snippet above.

1
export default connect(
2
  mapStateToProps,
3
  mapDispatchToProps
4
)(AddContact)

Instead of exporting the AddContact component directly, we're exporting a connected component. The connect provides addContact and newContact as props to the <AddContact/> component.

Simplifying the Code With Redux Hooks

We learnt how to connect our React component to the state in the previous section. The problem with the technique used above is the volume of code we had to write. We had to repeat functions to map the state to the action dispatcher and the component to the store. This may become an even bigger problem for large codebases.

Fortunately, some utilities were added to the React Redux library with the sole aim of decreasing the amount of boilerplate, and one of those utilities is the useSelector hook. With this hook, you don't need to map anything, nor do you need connect()—just import the hook and use it to access your application state anywhere in your app.

Demo Code

1
import {useSelector, useDispatch} from 'react-redux'
2
3
const AddContact = ({newContact, addContact}) => {
4
  const dispatch = useDispatch()
5
  const newContact = useSelector(state => state.contact.newContact)
6
  return (
7
    <div>
8
      {newContact.name} <br />
9
      {newContact.email} <br />
10
      {newContact.phone} <br />
11
      
12
      Are you sure you want to add this contact?
13
      <span onClick={dispatch(addContact)}> Yes </span>
14
    </div>
15
  )
16
}

Another hook—useDispatch()—was used above to dispatch an action on clicking the span element. Compared to the code in the previous section, you would agree that this version is cleaner and easier to understand. There is also no code repetition, making it very useful when dealing with large codebases.

You should note that these hooks were introduced starting from React Redux v7.1, so you must install either that or a later version in order to use them.

How to Connect React and Redux

Next, we're going to cover the steps that you need to follow to connect React and Redux.

Install the react-redux Library

Install the react-redux library if you haven't already. You can use NPM or Yarn to install it.

1
npm install react-redux --save 

Provide the Store to Your App Component

Create the store first. Then, make the store object accessible to your component tree by passing it as a prop to <Provider />.

index.js

1
import React from 'react';
2
import {render}from 'react-dom';
3
import { Provider } from 'react-redux'
4
import App from './App';
5
6
import makeStore from './store'
7
8
const store = makeStore();
9
10
render(
11
  <Provider store={store}>
12
    <App />
13
  </Provider>,

14
  document.getElementById('root')
15
)

Connect React Containers to Redux to Use State

The connect function is used to bind React containers to Redux. What that means is that you can use the connect feature to:

  1. subscribe to the store and map its state to your props
  2. dispatch actions and map the dispatch callbacks into your props

However, we'll no longer use the connect function to connect our store. Instead, we'll use the hooks to fetch from our store and dispatch actions when the need arises.

First, import useSelector, useDispatch, and the actions you want to dispatch into AddContact.jsx.

1
import { useSelector, useDispatch } from 'react-redux';
2
import { addContact, handleInputChange, toggleContactForm } from '../actions/';

Second, inside the AddContact() function, on the first line, import the state that the component needs and get the dispatcher:

1
const isHidden = useSelector(state => state.ui.isAddContactFormHidden)
2
const newContact = useSelector(state => state.contacts.newContact)
3
4
const dispatch = useDispatch()

The component is now equipped to read state from the store and dispatch actions. Next, the logic for handeInputChange, handleSubmit, and showAddContactBox should be updated as follows:

1
showAddContactBox() {
2
    dispatch(toggleContactForm())		
3
}
4
5
handleInputChange(event) {
6
	const target = event.target;
7
	const value = target.value;
8
	const name = target.name;
9
   	        
10
    dispatch(handleInputChange(name, value))    	
11
}
12
13
handleSubmit(e) {
14
	e.preventDefault();
15
	dispatch(toggleContactForm())    	
16
    dispatch(addContact())    			
17
}

We've defined the handler methods, but there is still one part missing—the conditional statement inside the render function.

1
return(
2
	<div>			
3
		{ isHidden === false ? enderForm(): <button onClick={showAddContactBox} className="btn"> Add Contact </button>}

4
	</div>

5
)

If isHidden is false, the form is rendered. Otherwise, a button gets rendered.

Displaying the Contacts

We've completed the most challenging part. Now, all that's left is to display these contacts as a list. The Contacts container is the best place for that logic.

1
import React from 'react';
2
import { useSelector } from 'react-redux'; 
3
/* Component import omitted for brevity */
4
5
function Contacts() {
6
  const contactList = useSelector(state => state.contacts.contactList)     
7
  
8
  const returnContactList = () => {
9
    return contactList;
10
  }
11
    
12
    return (
13
        <div>
14
     		<br />
15
         	<AddContact/>
16
         	<br />
17
          <ContactList contactList= {returnContactList()} />

18
        </div>

19
    );  
20
}
21
22
export default Contacts

We've gone through the same procedure that we followed above to connect the Contacts component with the Redux store in that we used useSelector to grab the needed branch of the state, which is contactList. That completes the integration of our app with the state of the Redux store.

What Next?

In the next post, we'll take a deeper look at middleware and start dispatching actions that involve fetching data from the server. Share your thoughts on the forum!

This post has been updated with contributions from Kingsley Ubah. Kingsley is passionate about creating content that educates and inspires readers. Hobbies include reading, football and cycling.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.