Beginner’s Guide To Redux

Purpose
In this tutorial we will look at how to set up Redux with your React app by creating a simple todo list application. By the end of this tutorial you should understand how to use Redux and have one possible project setup you can use for future projects.
Since there are many resources available that explain what Redux is and what it’s for it won’t be covered in this tutorial. Check out this blog most if you want to learn more: https://flaviocopes.com/redux/.
The tutorial is intended to help you get started writing a simple todo app.
The full code for this tutorial can be found on my Github page.
Getting Everything Setup
So that we don’t have to worry about Webpack and other configurations that might be necessary we will start the React project with the create-react-app CLI .
In your terminal navigate to directory you wish to create your todo-app in and execute the following commands:
npx create-react-app redux-todo-app
cd redux-todo-app
yarn start redux-todo-appWith npx we’re using the create-react-app CLI without having to install the package globally on our machines.
redux-todo-app is the name of the app you just created.
After navigating the the newly created directory you’re starting the server with yarn. At this point you should see a page that looks like this in your browser on port 3000:
Now you have successfully set up your React app. In the following steps we will look at how to set-up Redux.
Installing Dependencies for Redux
Before we start looking at code, let’s get everything we’ll be using installed.
Hitcontrol+c to exit out of the server. Then enter the following command:
yarn add redux react-reduxIf you check the package.json file and see the following two lines of code, you know that the dependencies were installed successfully:
“react-redux”: “5.0.7”,
“redux”: “4.0.0”Note that the version may be different, if you’re reading this tutorial at a later point in time.
Creating The Store
Now that the dependencies are installed we can start writing some code. Inside the folder src create a folder called store and initialize the folder with a file called ndex.js .
In src/store/index.js we will use a method from the Redux package to create the store.
import {createStore} from 'redux'
import todoListReducer from './reducers'const store = createStore(todoListReducer)export default store
Now, the store is created. We will continue setting everything up for now, and we’ll bring everything together once the set-up is done.
Creating An Action
Next, create a new file in the store: src/store/actions.js.
Actions are used to tell the reducer what to change in the store. They are just regular functions.
Let’s define our first action.
export const addTodoAction = content => ({
type: 'ADD_TODO',
payload: content
})When calling the action, we will pass the content of the new todo as the argument (more on that later).
Notice how the action returns an object with two items. The type is to tell the reducer what to do and the payload holds the content. That’s all we need in the action.
Creating A Reducer
Create a new file in the store: src/store/reducers.js.
Reducers are functions that can actually change the Redux store (the only way to change the store). It’s common to use a switch-statement in reducers to make the code more concise.
Let’s create a reducer that adds the content of our new todo to the store.
const todoListReducer = (state = {}, action) => {
switch (action.type) {
case 'ADD_TODO':
const newState = […state.todos]
newState.push(action.payload)
return {…state, todos: newState}
default:
return state
}
}export default todoListReducer
Here, in the case ADD_TODO we are taking the entire old state (just in case we already have todos), then concatenating it with the new todo which is in the action object, and finally returning it.
In the case that none of the action types match up, we have a default case that just returns the state as it is.

Giving Your App Access To Redux
Now, we only have a few steps left in order to get this to work.
First, we have to connect React and Redux and then we have to dispatch the action from our component.
We’ll start by connecting React and Redux (this is why we installed react-redux at the beginning).
The create-react-appcreated a file for us src/index.js. This is where we are going to tell our app about the store we just created. You’ll need to add the two last import statements and wrap the App component with Provider .
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { Provider } from 'react-redux'
import store from './store'ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById(‘root’)
)
It’s important that we wrap everything that should have access to the Redux store in the Provider component.
Provider takes the store as a prop.
Now Redux is all set up!
Let’s take a look at how to use the code we just wrote inside a React component.
Using Redux In A Component
For the sake of simplicity we will just edit the Appcomponent that was generated for us. It will have an input field to enter the new todo, a button to submit it, and an unordered list that will display all of our todos.
In src/App.js replace the code with the following:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = {
newTodo: ''
}
}
handleInputChange = e => {
this.setState({
newTodo: e.currentTarget.value
})
}
addNewTodo = () => {
// we will dispatch the action from here
}
render() {
return (
<div className="App">
<div>
<h1>Add New Todo</h1>
<input
type='text'
value={this.state.newTodo}
placeholder='New todo...'
onChange={this.handleInputChange}
/>
<button onClick={this.addNewTodo}>Submit</button>
</div>
<div>
<h1>Todo List</h1>
<ul>
<li>This is where our todos will appear later</li>
</ul>
</div>
</div>
);
}
}
export default App;Make sure you’ve started your server and then refresh your browser on localhost port 3000 (http://localhost:3000/)
It should look something like this:
This is the component before we’ve added connectivity with Redux. You can type in the input field but hitting submit won’t do anything yet.
Let’s change it, so that when you hit submit you add the new todo to the Redux store.
Before we can do that, we have to explicitly give our component access to the store. This is different from the Provider.
The Provider just told the components it surrounds that the store exists. Each component that wants to change the state needs to be connected to the store.
In src/App.js add add/change the following:
import {connect} from 'react-redux'
// the rest of the imports are here
// the rest of the component is here
export default connect()(App)Now App is connected to the store (literally). This means that we now have access to a bunch of new properties that come from the store.
One prop that we will use is the dispatch()function. Recall that actions must be dispatched in order for them to work.
We want to pass the this.state.newTodo into the action we created before which will then call the reducer, which will change the global state/Redux store. This should happen upon clicking submit.
addNewTodo = () => {
this.props.dispatch(addTodoAction(this.state.newTodo))
}Don’t forget to import the actions from store/actions .
To see if this was successful, go to the reducer and try logging the newState before returning it. Here’s what it would look like if you click submit “Drink lots of coffee”.
['Drink lots of coffee']Rendering The New Todos
All that left is rendering our new todos in the todo list.
In App.js you will need another function to be able to render the todos from the store.
After the class App add this code and call the function in the connect:
const mapStateToProps = state => ({
todos: state.todos
})
export default connect(mapStateToProps)(App)mapStateToProps literally maps the Redux state to the props of the component. This means that the todos is now accessible by calling this.props.todos.
Now let’s update the <ul> so that it render the todo list dynamically.
// …
<div>
<h1>Todo List</h1>
<ul>
<li>This is where our todos will appear later</li>
{this.props.todos ?
this.props.todos.map(todo => {
return (
<li key={todo}>{todo}</li>
)
})
}
</ul>
</div>After hitting submit, your component should re-render and display the new todo underneath the placeholder.
To see all the code from this tutorial check out my Github page.
Conclusion
By now, you should have a working example of a very simple todo list that allows you to add todos with Redux, which appear immediately after hitting the submit button.