Connect Your React App to Redux in 5 Steps

William Vetter
4 min readDec 4, 2020

Using React is wonderful — it’s responsive, easy(ish) to understand, and has a lot of well thought-out features that improve the ‘quality of life’ for would-be developers.

As applications grow larger, it becomes more and more complex to pass ‘state’ or functions through components — imagine having to pass down a simple function down through a dozen (or more) components through props. This gets worse and worse as we begin to work on enterprise-level applications.

Enter Redux.

Redux is a state management tool that solves the problem we just talked about (along with a few others).

The setup adds a bit more complexity to your application, but if your application grows or is planned to grow larger than your usual personal project, it will save a ton of time.

After npm install react and npm install react-redux, let’s begin implementing Redux.

1. Import Redux features into your main file:

##### ./src/index.js #####import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import { createStore } from 'redux'
import manageToDos from './reducers/manageToDos';


const store = createStore(manageToDos, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

For added clarity, I’ve bolded the changes to our usual formula within index.js.

Here, we’re doing a few things:

Importing { Provider } and { createStore } from ‘react-redux’ and ‘redux’ libraries, respectively.

  • Provider = used to wrap our <App /> component in, passing in our create const store as a prop called ‘store’.
  • createStore = used to create and connect our store, using a reducer and an expression to utilize Chrome Redux DevTools.

Importing a reducer, manageToDos.

  • Creating a store variable that points to the output of Redux’s createStore() function. This is connected to our reducer, manageToDos, and an extension that allows us to view Redux in Google Chrome.

2. Create a Reducer to manage State (and Actions)

A reducer does 2 things:

  • It takes in the current state, and an action
  • Based on that action, it will return a copy of the new state with the designated changes.

Let’s take a look:

##### ./src/reducers/manageToDos.js #####export default function manageToDos(state = {
todos: []
}, action) {
switch (action.type) {

case 'ADD_TODO':
return {
...state,
todos: [...state.todos, action.todo]
}

default:
return state;

}
};

Here, our reducer, manageToDos, is simply a pure function.

When this reducer is sent an action, it will run through it’s switch statement, checking whether or not it has a case that is equal to the action.type it was sent.

How is this reducer sent an action? What are actions? Read on to:

3. Create Actions

Actions, like reducers, are pure functions. The output of these functions, a POJO (or Plain Ol’ Javascript Object), are typically structure to have 2 things:

  • type: Type will be a string, all caps, that describes what the action is supposed to do. (e.g. type: ‘ADD_TODO’)
  • and a payload, or data of some sort. In this case, it will be the ‘todo’ object that we wish to add to our state.

Let’s take a look:

##### ./src/actions/todoActions.js #####export const addToDo = (newToDo) => {
return {
type: 'ADD_TODO',
newToDo
};
};

Now, how do we send these lovely actions to our reducer? This is where the magic comes in.

4. Connect Your Components to Write to the Redux Store

##### ./src/components/ToDoForm.js ######import React, { Component } from 'react';
import { addToDo } from '../actions/todoActions';
import { connect } from 'react-redux';


export class ToDoForm extends Component {

state = {
todo: ''
}

handleChange = event => {
this.setState({
todo: event.target.value
});
}

handleSubmit = event => {
event.preventDefault();

this.props.addToDo(this.state)
}

render() {
return(
<form onSubmit={this.handleSubmit}>
<input type='text' name='todo'
value={this.state.todo}
onChange={this.handleChange}/>

<input type="submit"/>
</form>
);
}
};

export default connect(null, { addToDo })(ToDoForm)

Above, we have a simple controlled component, called ‘ToDoForm’.

The only differences, again, have been highlighted in bold:

We’re importing the action to use inside of this component, { addToDo }, and a function, { connect }, from ‘redux’.

Now, to connect our app to the store, we change the bottom-line export to:

export default connect()(ToDoForm)

connect() takes 2 arguments:

  • mapStateToProps, which will read the state of the Redux store, and return whatever information we like to be accessible within props.
  • mapDispatchToProps, which will connect whatever actions we’ve imported to talk to our Redux store.

Here, we’re solely concerned with sending information to our state, so we’ve left the first argument null, and with short-hand, we can write { addToDo } to tell our component that we’ll be dispatching this action to our reducer if invoked. This allows the component, ToDoForm, to access the ‘addToDo’ function within it’s props.

Finally, inside of handleSubmit(), rather than sending this information off somewhere, we’ll instead say:

this.props.addToDo(this.state)

This fires off a chain of events. Namely:

The action is called, producing a POJO →

→Action is sent to Reducer→

→New State is produced

Now where will we be able to see these current or new state changes? In our To Do List!

5. Connect Your Components to Read from the Redux Store

##### ./src/components/ToDoList.js #####import React, { Component } from 'react';
import { connect } from 'react-redux';

class ToDoList extends Component {

render() {
return (
<div>
<ul>
{
this.props.todos.map((item, index) =>
return <li key={index}> {item.todo} </li>)
}
</ul>
</div>
);
}
};

const mapStateToProps = state => {
return { todos: state.todos }
}


export default connect(mapStateToProps)(ToDoList);

Not too much bold text here! Meaning not many changes to set up and listen to our Redux store!

Here, we’ve a simple component that simply reads whatever is in the state, and makes a <li></li> for each one.

Before, we’d usually have a state in ‘App.js’, where we’d then pass that in as props to whatever component needs them.

Instead, we’re getting that state through the connect() at the bottom. Whereas this time, we’re going to use the first argument, mapStateToProps. This function reads whatever the state is from the Redux Store, and maps that to props. Finally allowing it to be available in our ToDoList component!!

--

--

William Vetter
0 Followers

Full Stack Developer based in Ann Arbor, Michigan. Javascript, Ruby, ReactJS, React Native, and more! 2008–2013 Super Smash Bros professionále