React Redux Tutorial for Beginners: The Definitive Guide (2018)

The simplest React Redux tutorial I wish I had when I started learning

The Redux logo - React Redux tutorial

When I first started learning Redux I wish I could find the simplest tutorial ever.

Despite the great resources out there I couldn’t wrap my head around some of the Redux concepts.

I knew what’s the state. But actions, action creators, and reducers? They were obscure for me.

Last but not least I didn’t know how to glue React and Redux together.

During those days I started writing my own React Redux tutorial and since then I learned a lot.

I taught myself the Redux fundamentals by writing this guide. I hope it’ll be useful for all those learning React and Redux.

Enjoy the reading!

React Redux tutorial: who this guide is for

The following React Redux guide is exactly what you’re looking for if:

  • you have a good grasp of Javascript, ES6, and React
  • you’re looking forward to learn Redux in the most simple way

React Redux tutorial: what you will learn

In the following guide you will learn:

  1. what is Redux
  2. how to use Redux with React

React Redux tutorial: a minimal React development environment

To follow along with the guide you should have a good grasp of Javascript, ES6, and React.

Also, create a minimal React development environment before starting off.

Feel free to use webpack or Parcel.

To get started with webpack clone my Github repo:

git clone https://github.com/valentinogagliardi/webpack-4-quickstart.git

Remove the file ./src/App.jsfrom the repo before moving forward.

React Redux tutorial: what is the state?

To understand what is Redux you must first understand what is the state.

If you have ever worked with React the term state should be no surprise to you.

I guess you already wrote some stateful React component:

import React, { Component } from "react";

class ExampleComponent extends Component {
  constructor() {
    super();

    this.state = {
      articles: [
        { title: "React Redux Tutorial for Beginners", id: 1 },
        { title: "Redux e React: cos'è Redux e come usarlo con React", id: 2 }
      ]
    };
  }

  render() {
    const { articles } = this.state;
    return <ul>{articles.map(el => <li key={el.id}>{el.title}</li>)}</ul>;
  }
}

A stateful React component is a Javascript ES6 class.

Every stateful React component carries its own state.

In a React component the state holds up data and the component might render such data to the user.

The state could also change in response to actions and events: in React you can update the local component’s state with setState.

But what is the state anyway?

The term state is not tied exclusively to React.

The state is all around you.

Even the simplest JavaScript application has a state.

Consider the following example:

the user clicks a button

a modal appears afterwards

Guess what, in this trivial interaction there is a state we must deal with.

We could describe the initial state as a plain JavaScript object:

var state = {
  buttonClicked: 'no',
  modalOpen: 'no'
}

And when the user clicks the button we have:

var state = {
  buttonClicked: 'yes',
  modalOpen: 'yes'
}

How do you keep track of those things in JavaScript besides storing the state in an object?

Is there a library that can help us tracking the state?

React Redux tutorial: what problem does Redux solve?

A typical JavaScript application is full of states. And you didn’t even know.

Here are some examples of state:

  • what the user sees (data)
  • what data are we fetching
  • what URL are we showing to the user
  • what items are selected inside the page
  • are there errors in the applications? That’s state too

State is everywhere in JavaScript.

As you can see even the simplest JavaScript application has a state.

But can you imagine how much state a React application has?

Yeah, you can get by with keeping the state within a parent React component.

As long as the application remains small.

Then things will become tricky.

Even a silly to-do list could become unmanageable if you starting passing the state up and down.

Who wants a bloated React component?

Not only, I’d say that the frontend shouldn’t know about the business logic. Ever.

So what are the alternatives for managing the state of a React component?

Redux is one of them.

Redux solves a problem that might not be clear in the beginning: it helps giving each React component the exact piece of state it needs.

Redux holds up the state within a single location.

Also with Redux the logic for fetching and managing the state lives outside React.

The benefits of this approach might be not so evident. Things will look clear as soon as you’ll get your feet wet with Redux.

In the next section we’ll see why you should learn Redux and when to use Redux within your applications.

React Redux tutorial: should I learn Redux?

Are you trying to learn Redux but you’re going nowhere?

Redux literally scares most beginners. But that shouldn’t be your case.

Redux is not that hard. The key is: don’t rush learning Redux just because.

You should start learning Redux if you’re motivated and passionate about it.

Take your time.

I started to learn Redux because:

  • I was 100% interested in learning how Redux works
  • I was eager to improve my React skills
  • the combination React/Redux is ubiquitous
  • Redux is framework agnostic. Learn it once, use it everywhere (Vue JS, Angular)

Learning Redux or an equivalent state management library is a must.

Another truth is: real world JavaScript applications make always use of a state management library.

State is so pervasive and hard that state management in JS is still an unsolved problem.

The amount of libraries that come out almost daily is a proof.

Redux is just a library among the others, yet it is one of the most important.

Will Redux disappear in the future? Maybe.

But the patterns will stick forever.

Would you neglet learning OOP with PHP just because PHP is not “trendy” anymore?

I advise not doing so.

The same with Redux.

You should learn the patterns for managing UI state because they will be invaluable in your career.

React Redux tutorial: should I use Redux?

Using Redux or Flux (or Mobx) for state management is up to you.

Maybe you need none of these libraries. They have a cost: they add another layer of abstraction to your application.

But I prefer thinking about Redux as an investment, not as a cost.

Another common question for Redux beginners is: how do you know when you’re ready to use Redux in your application?

If you think about it there is no rule of thumb for determining when you do need Redux for managing the state.

Redux also offers a lot of convenience for a JavaScript developer. Debugging, action replaying. And much more.

When I start a new React project I’m always tempted to add Redux straight away. But …

As developers we overengineer our code automatically.

So, when should you add Redux to a project?

Before picking Redux take your time to explore alternative patterns. In particular try to get the most out of React’s state and props.

Dave Ceddia has a nice writeup with a lot of great insights for using children props as an alternative before reaching for Redux.

And don’t forget that a React project can be easily refactored to include Redux later.

What I found is that you should consider using Redux when:

  • multiple React components needs to access the same state but do not have any parent/child relationship
  • you start to feel awkward passing down the state to multiple components with props

If that makes still no sense for you do not worry, I felt the same.

Dan Abramov says “Flux libraries are like glasses: you’ll know when you need them.”

And in fact it worked like that for me.

Whatever Dan Abramov says to do
Courtesy of dev.to

Before going further take your time to understand what problem does Redux solve and whether you’re motivated or not to learn it.

Be aware that Redux is not useful for smaller apps. It really shines in bigger ones. Anyway, learning Redux even if you’re not involved in something big wouldn’t harm anyone.

In the next section we’ll start building a proof of concept to introduce:

  • the Redux fundamental principles
  • Redux alongside with React

React Redux tutorial: getting to know the Redux store

Actions. Reducers. I kind of knew about them. But one thing wasn’t clear to me: how were all the moving parts glued together?

Were there some minions or what?

React Redux tutorial. There are no minions in Redux

In Redux there are no minions (unfortunately).

The store orchestrates all the moving parts in Redux. Repeat with me: the store.

The store in Redux is like the human brain: it’s kind of magic.

The Redux store is fundamental: the state of the whole application lives inside the store.

So to start playing with Redux we should create a store for wrapping up the state.

Move into your React development environment and install Redux:

cd webpack-4-quickstart/
npm i redux --save-dev

Create a directory for the store:

mkdir -p src/js/store

Create a new file named index.jsin src/js/storeand finally initialize the store:

// src/js/store/index.js

import { createStore } from "redux";
import rootReducer from "../reducers/index";

const store = createStore(rootReducer);

export default store;

createStore is the function for creating the Redux store.

createStore takes a reducer as the first argument, rootReducer in our case.

You may also pass an initial state to createStore. But most of the times you don’t have to. Passing an initial state is useful for server side rendering. Anyway, the state comes from reducers.

NOTE: see Reducer returned undefined during initialization

So what does exactly a reducer do?

In Redux reducers produce the state. The state is not something you create by hand.

Armed with that knowledge let’s move on to our first Redux reducer.

React Redux tutorial: getting to know Redux reducers

While an initial state is useful for SSR, in Redux the state must return entirely from reducers.

Cool but what’s a reducer?

Redux Logo

A reducer is just a Javascript function. A reducer takes two parameters: the current state and an action (more about actions soon).

The third principle of Redux says that the state is immutable and cannot change in place.

This is why the reducer must be pure. A pure function is one that returns the exact same output for the given input.

In plain React the local state changes in place with setState. In Redux you cannot do that.

Creating a reducer is not that hard. It’s a plain Javascript function with two parameters.

In our example we’ll be creating a simple reducer taking the initial state as the first parameter. As a second parameter we’ll provide action. As of now the reducer will do nothing than returning the initial state.

Create a directory for the root reducer:

mkdir -p src/js/reducers

Then create a new file named index.jsin the src/js/reducers:

// src/js/reducers/index.js

const initialState = {
  articles: []
};

const rootReducer = (state = initialState, action) => state;

export default rootReducer;

I promised to keep this guide as simple as possibile. That’s why our first reducer is a silly one: it returns the initial state without doing anything else.

Notice how the initial state is passed as a default parameter.

In the next section we’ll add an action to the mix. That’s where things will become interesting.

React Redux tutorial: getting to know Redux actions

Redux reducers are without doubt the most important concept in Redux. Reducers produce the state of the application.

But how does a reducer know when to produce the next state?

The second principle of Redux says the only way to change the state is by sending a signal to the store.This signal is an action. “Dispatching an action” is the process of sending out a signal.

Now, how do you change an immutable state? You won’t. The resulting state is a copy of the current state plus the new data.

That’s a lot to know.

The reassuring thing is that Redux actions are nothing more than Javascript objects. This is what an action looks like:

{
  type: 'ADD_ARTICLE',
  payload: { name: 'React Redux Tutorial', id: 1 }
}

Every action needs a type property for describing how the state should change.

You can specify a payload as well. In the above example the payload is a new article. A reducer will add the article to the current state later.

It is a best pratice to wrap every action within a function. Such function is an action creator.

Let’s put everything together by creating a simple Redux action.

Create a directory for the actions:

mkdir -p src/js/actions

Then create a new file named index.jsin src/js/actions:

// src/js/actions/index.js

export const addArticle = article => ({ type: "ADD_ARTICLE", payload: article });

So, the type property is nothing more than a string.

The reducer will use that string to determine how to calculate the next state.

Since strings are prone to typos and duplicates it’s better to have action types declared as constants.

This approach helps avoiding errors that will be difficult to debug.

Create a new directory:

mkdir -p src/js/constants

Then create a new file named action-types.jsinto the src/js/constants:

// src/js/constants/action-types.js

export const ADD_ARTICLE = "ADD_ARTICLE";

Now open up again src/js/actions/index.jsand update the action to use action types:

// src/js/actions/index.js

import { ADD_ARTICLE } from "../constants/action-types";

export const addArticle = article => ({ type: ADD_ARTICLE, payload: article });

We’re one step closer to have a working Redux application. Let’s refactor our reducer!

React Redux tutorial: refactoring the reducer

Before moving forward let’s recap the main Redux concepts:

  • the Redux store is like a brain: it’s in charge for orchestrating all the moving parts in Redux
  • the state of the application lives as a single, immutable object within the store
  • as soon as the store receives an action it triggers a reducer
  • the reducer returns the next state

What’s a Redux reducer made of?

A reducer is a Javascript function taking two parameters: the state and the action.

A reducer function may have a switch statement (but I prefer using if).

View this post on Instagram

❓ At first the most confusing parts of Redux is understanding what reducers do. Turns out reducers are just JavaScript functions! A reducer takes two parameters: the current state and an action. So given the actual state, a reducer could return the next state by looking at the action type. Pay attention to Object.assign. It's a method for copying one or more source objects into a new fresh object. In the example we copy into a new object the actual state, plus the properties we want to change. Then the object gets returned! . . . . . #redux #reduxjs #javascript #es6 #frontend #webdev #webdevelopment #codinglife #codelife #code #reacttraining #react #reactjs #javascripttraining #tech #developer #devcoach #html #css #coaching #tutor #education #privatetutor #tutorial #coder #geek #geeklife #programmerslife #codingisfun #100daysofcode

A post shared by Valentino Gagliardi (@valentinogagliardi) on

The reducer calculates the next state depending on the action type. Moreover, it should return at least the initial state when no action type matches.

When the action type matches a case clause the reducer calculates the next state and returns a new object. Here’s an excerpt of the code:

// ...
  switch (action.type) {
    case ADD_ARTICLE:
      return { ...state, articles: [...state.articles, action.payload] };
    default:
      return state;
  }
// ...

The reducer we created in the previous section does nothing than returning the initial state. Let’s fix that.

Open up src/js/reducers/index.jsand update the reducer as follow:

import { ADD_ARTICLE } from "../constants/action-types";

const initialState = {
  articles: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
      state.articles.push(action.payload);
      return state;
    default:
      return state;
  }
};

export default rootReducer;

What do you see here?

Although it’s valid code the above reducer breaks the main Redux principle: immutability.

Array.prototype.push is an impure function: it alters the original array.

Making our reducer compliant is easy. Using Array.prototype.concat in place of Array.prototype.push is enough to keep the initial array immutable:

import { ADD_ARTICLE } from "../constants/action-types";

const initialState = {
  articles: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
      return { ...state, articles: state.articles.concat(action.payload) };
    default:
      return state;
  }
};

export default rootReducer;

We’re not done yet! With the spread operator we can make our reducer even better:

import { ADD_ARTICLE } from "../constants/action-types";

const initialState = {
  articles: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
      return { ...state, articles: [...state.articles, action.payload] };
    default:
      return state;
  }
};

export default rootReducer;

In the example above the initial state is left utterly untouched.

The initial articles array doesn’t change in place.

The initial state object doesn’t change as well. The resulting state is a copy of the initial state.

There are two key points for avoiding mutations in Redux:

The object spread operator is still in stage 3. Install Object rest spread transform to avoid a SyntaxError Unexpected token when using the object spread operator in Babel:

npm i --save-dev babel-plugin-transform-object-rest-spread

Open up .babelrcand update the configuration:

{
    "presets": ["env", "react"],
    "plugins": ["transform-object-rest-spread"]
}

Redux protip: the reducer will grow as your app will become bigger. You can split a big reducer into separate functions and combine them with combineReducers

In the next section we’ll play with Redux from the console. Hold tight!

React Redux tutorial: Redux store methods

This will be super quick, I promise.

I want you to play with the brower’s console for gaining a quick understanding of how Redux works.

Redux itself is a small library (2KB). The Redux store exposes a simple API for managing the state. The most important methods are:

  • getState for accessing the current state of the application
  • dispatch for dispatching an action
  • subscribe for listening on state changes

We will play in the brower’s console with the above methods.

To do so we have to export as global variables the store and the action we created earlier.

Create src/js/index.jsand update the file with the following code:

import store from "../js/store/index";
import { addArticle } from "../js/actions/index";

window.store = store;
window.addArticle = addArticle;

Open up src/index.jsas well, clean up its content and update it as follows:

import index from "./js/index"

Now run webpack dev server (or Parcel) with:

npm start

head over http://localhost:8080/ and open up the console with F12.

Since we’ve exported the store as a global variable we can access its methods. Give it a try!

Start off by accessing the current state:

store.getState()

output:

{articles: Array(0)}

Zero articles. In fact we haven’t update the initial state yet.

To make things interesting we can listen for state updates with subscribe.

The subscribe method accepts a callback that will fire whenever an action is dispatched. Dispatching an action means notifying the store that we want to change the state.

Register the callback with:

store.subscribe(() => console.log('Look ma, Redux!!'))

To change the state in Redux we need to dispatch an action. To dispatch an action you have to call the dispatch method.

We have one action at our disposal: addArticle for adding a new item to the state.

Let’s dispatch the action with:

store.dispatch( addArticle({ name: 'React Redux Tutorial for Beginners', id: 1 }) )

Right after running the above code you should see:

Look ma, Redux!!

To verify that the state changed run again:

store.getState()

The output should be:

{articles: Array(1)}

And that’s it. This is Redux in its simplest form.

Was that difficult?

Take your time to explore these three Redux methods as an exercise. Play with them from the console:

  • getState for accessing the current state of the application
  • dispatch for dispatching an action
  • subscribe for listening on state changes

That’s everything you need to know for getting started with Redux.

Once you feel confident head over the next section. We’ll go straight to connecting React with Redux!

React Redux tutorial: connecting React with Redux

After learning Redux I realized it wasn’t so complex.

I knew how to access the current state with getState.

I knew how to dispatch an action with dispatch

I knew how to listen for state changes with subscribe

Yet I didn’t know how to couple React and Redux together.

I was asking myself: should I call getState within a React component? How do I dispatch an action from a React component? And so on.

Redux on its own is framework agnostic. You can use it with vanilla Javascript. Or with Angular. Or with React. There are bindings for joining together Redux with your favorite framework/library.

For React there is react-redux.

Before moving forward install react-redux by running:

npm i react-redux --save-dev

To demonstrate how React and Redux work together we’ll build a super simple application. The application is made of the following components:

  • an App component
  • a List component for displaying articles
  • a Form component for adding new articles

(The application is a toy and it does nothing serious other than displaying a list and a form for adding new items. Nonetheless it’s still a good starting point for learning Redux)

React Redux tutorial: react-redux

react-redux is a Redux binding for React. It’s a small library for connecting Redux and React in an efficient way.

The most important method you’ll work with is connect

What does react-redux’s connect do? Unsurprisingly it connects a React component with the Redux store.

You will use connect with two or three arguments depending on the use case. The fundamental things to know are:

  • the mapStateToProps function
  • the mapDispatchToProps function

What does mapStateToProps do in react-redux? mapStateToProps does exactly what its name suggests: it connects a part of the Redux state to the props of a React component. By doing so a connected React component will have access to the exact part of the store it needs.

What does mapDispatchToProps do in react-redux? mapDispatchToProps does something similar, but for actions. mapDispatchToProps connects Redux actions to React props. This way a connected React component will be able to dispatch actions.

Is everything clear? If not, stop and take your time to re-read the guide. I know it’s a lot to learn and it requires time. Don’t worry if you don’t get Redux right know. It will click sooner or later.

In the next section we’ll finally get our hands dirty!

React Redux tutorial: App component and Redux store

We saw that mapStateToProps connects a portion of the Redux state to the props of a React component. You may wonder: is this enough for connecting Redux with React? No, it’s not.

To start off connecting Redux with React we’re going to use Provider.

Provider is an high order component coming from react-redux.

Using layman’s terms, Provider wraps up your React application and makes it aware of the entire Redux’s store.

Why so? We saw that in Redux the store manages everything. React must talk to the store for accessing the state and dispatching actions.

Enough theory.

Open up src/js/index.js, wipe out everything and update the file with the following code:

import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import store from "./store/index";
import App from "./components/App";

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("app")
);

You see? Provider wraps up your entire React application. Moreover it gets the store as a prop.

Now let’s create the App component since we’re requiring it. It’s nothing special: App should import a List component and render itself.

Create a directory for holding the components:

mkdir -p src/js/components

and a new file named App.jsinside src/js/components:

// src/js/components/App.js
import React from "react";
import List from "./List";

const App = () => (
  <div className="row mt-5">
    <div className="col-md-4 offset-md-1">
    <h2>Articles</h2>
      <List />
    </div>
  </div>
);

export default App;

Take moment and look at the component without the markup:

import React from "react";
import List from "./List";

const App = () => (
      <List />
);

export default App;

then move on to creating List.

React Redux tutorial: List component and Redux state

We have done nothing special so far.

But our new component, List, will interact with the Redux store.

A brief recap: the key for connecting a React component with Redux is connect.

Connect takes at least one argument.

Since we want List to get a list of articles it’s a matter of connecting state.articleswith the component. How? With mapStateToProps.

Create a new file named List.jsinside src/js/components. It should look like the following:

// src/js/components/List.js

import React from "react";
import { connect } from "react-redux";

const mapStateToProps = state => {
  return { articles: state.articles };
};

const ConnectedList = ({ articles }) => (
  <ul className="list-group list-group-flush">
    {articles.map(el => (
      <li className="list-group-item" key={el.id}>
        {el.title}
      </li>
    ))}
  </ul>
);

const List = connect(mapStateToProps)(ConnectedList);

export default List;

The List component receives the prop articleswhich is a copy of the articlesarray. Such array lives inside the Redux state we created earlier. It comes from the reducer:

const initialState = {
  articles: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
      return { ...state, articles: [...state.articles, action.payload] };
    default:
      return state;
  }
};

Then it’s a matter of using the prop inside JSX for generating a list of articles:

{articles.map(el => (
  <li className="list-group-item" key={el.id}>
    {el.title}
  </li>
))}

React protip: take the habit of validating props with PropTypes

Finally the component gets exported as List. List is the result of connecting the stateless component ConnectedList with the Redux store.

A stateless component does not have its own local state. Data gets passed to it as props

Still confused? I was too. Understanding how connect works will take some time. Fear not, the road to learn Redux is paved with “ah-ha” moments.

I suggest taking a break for exploring both connect and mapStateToProps.

Once you’re confident about them head over the next section!

React Redux tutorial: Form component and Redux actions

The Form component we’re going to create is a bit more complex than List. It’s a form for adding new items to our application.

Plus it is a stateful component.

A stateful component in React is a component carrying its own local state

A stateful component? “Valentino, we’re talking about Redux for managing the state! Why on earth would you give Form its own local state??”

Even when using Redux it is totally fine to have stateful components.

Not every piece of the application’s state should go inside Redux.

In this example I don’t want any other component to be aware of the Form local state.

And that’s perfectly fine.

What does the component do?

The component contains some logic for updating the local state upon a form submission.

Plus it receives a Redux action as prop. This way it can update the global state by dispatching the addArticle action.

Create a new file named Form.jsinside src/js/components. It should look like the following:

// src/js/components/Form.js
import React, { Component } from "react";
import { connect } from "react-redux";
import uuidv1 from "uuid";
import { addArticle } from "../actions/index";

const mapDispatchToProps = dispatch => {
  return {
    addArticle: article => dispatch(addArticle(article))
  };
};

class ConnectedForm extends Component {
  constructor() {
    super();

    this.state = {
      title: ""
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ [event.target.id]: event.target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    const { title } = this.state;
    const id = uuidv1();
    this.props.addArticle({ title, id });
    this.setState({ title: "" });
  }

  render() {
    const { title } = this.state;
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="form-group">
          <label htmlFor="title">Title</label>
          <input
            type="text"
            className="form-control"
            id="title"
            value={title}
            onChange={this.handleChange}
          />
        </div>
        <button type="submit" className="btn btn-success btn-lg">
          SAVE
        </button>
      </form>
    );
  }
}

const Form = connect(null, mapDispatchToProps)(ConnectedForm);

export default Form;

What can I say about the component? Besides mapDispatchToProps and connect it’s standard React stuff.

mapDispatchToProps connects Redux actions to React props. This way a connected component is able to dispatch actions.

You can see how the action gets dispatched in the handleSubmit method:

// ...
  handleSubmit(event) {
    event.preventDefault();
    const { title } = this.state;
    const id = uuidv1();
    this.props.addArticle({ title, id }); // Relevant Redux part!!
// ...
  }
// ...

Finally the component gets exported as Form. Form is the result of connecting ConnectedForm with the Redux store.

Side note: the first argument for connect must be nullwhen mapStateToProps is absent like in the Form example. Otherwise you’ll get TypeError: dispatch is not a function.

Our components are all set!

Update App to include the Form component:

import React from "react";
import List from "./List";
import Form from "./Form";

const App = () => (
  <div className="row mt-5">
    <div className="col-md-4 offset-md-1">
      <h2>Articles</h2>
      <List />
    </div>
    <div className="col-md-4 offset-md-1">
      <h2>Add a new article</h2>
      <Form />
    </div>
  </div>
);

export default App;

Install uuid with:

npm i uuid --save-dev

Now run webpack (or Parcel) with:

npm start

and head over to http://localhost:8080

You should see the following working POC:

React Redux tutorial demo. Nothing fancy but still useful for showing React and Redux at work

Nothing fancy but still useful for showing React and Redux at work!

The List component on the left is connected to the Redux store. It will re-render whenever you add a new item.

React Redux demo

Whoaaa!

You can find the code for that silly app (with prop-types and a splitted reducer) on my Github repo.

React Redux tutorial: wrapping up

I hope you’ll learn something from this guide. I tried my best to keep things as simple as possibile. I would love to hear your feedback in the comments below!

Redux has a lot of boilerplate and moving parts. Don’t get discouraged. Pick Redux, play with it and take your time to absorb all the concepts.

I went from zero to understanding Redux by small steps. You can do it too!

Also, take your time to investigate why and if you should use Redux in your application.

Either way think of Redux as an investment: learning it is 100% worthwile.

React Redux tutorial: courses and books for learning Redux

Want to level up your Redux skills once you finish my tutorial?

What’s the best Redux course you can buy?

What’s the best Redux book you can get?

Everybody can write an ebook or record a course these days.

But that does not make an expert.

I use React and Redux for a lot of project and yet I can’t beat the real experts out there.

People like Mark Erikson or Henrik Joreteg for example. They know their stuff.

So here’s my advice: stick with the experts when looking for JavaScript (and Redux) courses.

And here’s my suggestions for Redux.

The best Redux course? Practical Redux by Mark Erikson.

Mark is a Redux mantainer. He’ll show you important Redux concepts and techniques.

I don’t think there is a better person than Mark for learning Redux.

In Practical Redux you’ll learn how to:

  • control your UI behavior with Redux
  • use Redux-ORM to manage relational data in your Redux store
  • build a master/detail view to display and edit data
  • write custom advanced Redux reducer logic

Do yourself a favor, go check Practical Redux.

And now: books!

I had the privilege to put my hands on Human Redux by Henrik Joreteg.

React Redux tutorial Human Redux Book

So far I love the book.

Henrik has a lot of experience in building real world complex web applications.

He know Progressive Web Apps and how to use Redux.

Buy Henrik’s book if you want to:

  • learn real world Redux patterns
  • level up your Redux skills
  • learn about advanced Redux topics (middlewares, async actions, selectors, reselect)

I highly recommend Human Redux even if you’re just starting out with Redux.

It is a nice companion for my tutorial. Plus you’ll learn from a real expert.

Go grab it!

Other useful resources for learning Redux:

The official documentation: Redux Docs.

Resources for learning Redux by Mark Erikson.

Dan Abramov has a nice write-up that will help you understand if your application needs Redux

There’s also an interesting thread on dev.to with Dan explaining when is it time to stop managing state at the component level and switching to Redux

React Redux tutorial: resources for learning functional programming

Redux scares most beginners because it revolves around functional programming and pure functions.

Suggesting some resources is the best I can do since functional programming is beyond the scope of this guide. These are the best places for learning more about functional programming and pure functions:

Professor Frisby’s Mostly Adequate Guide to Functional Programming by Brian Lonsdorf

Functional-Light Javascript by Kyle Simpson

React Redux tutorial: async actions in Redux

I wasn’t sure whether talking about async actions would have been appropriate or not.

Most Redux beginners struggle to learn plain Redux. Handling async actions in Redux is not a straighforward task so better not overcomplicate things.

When you’ll feel confident about the core Redux concepts go check A Dummy’s Guide to Redux and Thunk in React by Matt Stow. It’s a nice introduction to handling API calls in Redux with redux-thunk.

Thanks for reading and happy coding!

Valentino Gagliardi

Valentino Gagliardi

I help busy people to learn Web Development and JavaScript - DevOps Consultant
Valentino Gagliardi

240 Replies to “React Redux Tutorial for Beginners: The Definitive Guide (2018)”

      1. Thanks for the hard work on the tutorial Valentino! Can you please fix the errors Julia mentioned below, as this is supposed to be a beginner’s tutorial, but most beginners will get lost when they encounter these issues and not be able to complete it? It took me a while to debug the arrow functions one – I was able to with this answer, but I’m sure there’s a newer way: https://stackoverflow.com/questions/42046496/cant-get-arrow-functions-to-work-react-babel-webpack-es6. Thank you!

        1. Hi Ivan

          are you talking about this? “using arrow functions to bind methods didn’t work”. There are no arrow function for binding methods in the tutorial. handleChange and handleSubmit are regular class methods.

      2. the explaination for the connect function was not sufficient. I could not understand whats really happening in the connectedList function.

  1. Just finished the tutorial, it was extremely helpful in breaking everything into discrete steps. + so many upvotes! As a beginner, it was great to see everything explained clearly (e.g. why push bad, spread operator good). I didn’t even know that objects could have spread operators, but makes a lot of sense.

    Some comments as I was running the code:

    1. I was having some issues with the paths specified. I used “./js/store/index” instead of “../js/store/index”.

    2. Was having an issue with exporting App to src/index.js so I deleted the `export default App` statement and did `export const App` at the top and imported { App } like so.

    3. Interestingly, using arrow functions to bind methods didn’t work. It may have something to do with babel presents specified. After googling a bit, it didn’t seem like best practice anyways for performance (oops, been writing React wrong!).

    Other comments:

    1. Would be great to see an article for redux-thunk and redux-saga, comparing the two.

    2. Would be great to learn about how to test Redux with React.

    3. Would be great to see a fullstack example with Node.

    Thank you so much for sharing your knowledge!

    1. Julia: thanks for your comment! It’s really rewarding to see other people learning from my tutorials.

      This Redux tutorial took me 1 week. It was written specifically for other fellow developers like you.

      I appreciate your suggestions! Stay tuned on this blog, maybe I’ll put something together about redux-thunk and redux-saga.

      Happy coding!

      1. Hi. Great little tutorial! Well done.
        My little App now follows your patterns. I have a few components/containers
        that use Redux/connect.

        The router doesn’t seem to want to play with connect(). Any ideas?

    2. On 3) Arrow functions in ES6 syntax make `this` refer to the lexical context and not the usual execution/invocation or the bound, context if it the case. Common mistake when starting on ES6.

      As a principle, as long as `this` is used, it is more cautious to stick to old fashion syntax, unless it is really what is expected, like some cases of self-invoking functions.

      Beside that, I really appreciated this tutorial.

  2. Thanks for the tutorial, it also worked well for an experienced developer new to redux

    A few tiny tweaks:
    * `Making our reducer complaint is easy.` <- Tiny typo, I think it should be “compliant"
    * .bablerc was already configured
    * I needed to run `npm install uuid`

  3. I avoided redux in my first app because it looked too complicated.
    When I did decide to learn it, I went from pole to post trying to find the right book, video, tutorial, article…you name it..anything that would help me grasp the concept (I am a seasoned developer) …but everyone trying to teach redux just seemed to get into very convoluted jargon, diagrams and explanations.
    I sat down with this page, your page, open and in one afternoon I am all set. I know redux (imagine Neo saying “I know kung fu!”)
    Thank you so much for a straight forward tutorial. Now I can go back and end expand my knowledge on the once-upon-a-time-complicated tutorials!

  4. Fantastic tutorial, Thank you Valentino.

    I just have doubt in this sentence that you said: “A pure function is one that returns the exact same output for the given input.”

    Is that the same term with side effects or it’s another principle of pure functions?

    1. Because as I noticed you are talking about immutability but the provided definition is not about side effects. That’s why I confused.

      Anyway, thank you for the amazing tutorial.

    2. Pedro, thanks for stopping by!

      A pure function is a function that:

      – returns the same output for the given input

      – has no side effects

      Those are two distinct principles, yet they are both about functional programming.

      Immutability is another functional programming concept and is strictly related to pure functions.

      So, yeah, they’re intertwined with each other as you can see!

  5. Outstanding article!!! cleared my major confusion with React/Redux which i was struggling for few weeks which is mapDispatchToProps usage in the container component.Now i will play with your repo to get better understanding.

  6. Thank you for this tutorial and all your other tutorials on react. I am an angular developer looking to explore more of reactjs and I find your tutorials very easy to follow as a react beginner. I was unsure on how to begin learning redux and this has given me a starting point.
    Please keep up the good work. cheers

  7. Hi, I think I am missing something, but I am getting a ‘module build failed’ error

    Module build failed: SyntaxError: Unexpected token (8:15)

    8 | return { …state, articles: […state.articles, action.payload] };

    for some reason it doesn’t like returning this object with state.

    Am i somehow missing babel or webpack, from the minimal template i downloaded from you?

    so far this is a wonderful tutorial!

  8. Hi disregard thelast comment, I missed the .babelrc

    however I am trying to follow your console redux part, and I amgetting this error wheni try and type the following:

    store.dispatch( addArticle({ name: “React Redux Tutorial for Beginners”, id: 1 }) )

    Error: Actions may not have an undefined “type” property. Have you misspelled a constant?

    why is this happening?

    1. Same error message here: “Actions may not have an undefined “type” property. Have you misspelled a constant?”

      Love the approach in explaining the seemingly mysterious concept, plain and simple, till I ran into the error message. How do you debug the problem?

  9. A small mistake: In the example of initial reducer that breaks the immutability
    return { …state, articles: state.articles.push(action.payload) };
    actually returns { articles: 1 } (the number of articles, not the array of article)

    So it probably should rephrase to (not really a good situation to use spread op here for the whole article, in my opinion)
    state.articles.push(action.payload)
    return state

  10. Great article! One of the simplest one on Redux I could find to get the concepts right.. Something I’m struggling to understand though in the reducer code, how exactly are we returning two values? (state,articles)? Is this some concept on functional programming?

    return { …state, articles: […state.articles, action.payload] };

  11. This is wonderful! mapStateToProps and mapDispatchToProps finally clicked after seeing them in two different components. Best explanation of react/redux I have read.

  12. Thanks a lot for putting this together and sharing it! It was very generous of you. Redux comes with a paradigm shift that can seem daunting at first but this tutorial really helps!

  13. Good tutorial, thanks for writing, I found it useful.

    If I can suggest one small improvement – it would be helpful if you explained why mapDispatchToProps is useful (so the component doesn’t have to know about redux / dispatch) and also what happens on the form submit. I got confused for a while thinking this.props.addArticle was the action creator in actions/index.js when in fact it comes from mapDispatchToProps.

  14. this is forever the best learning material I found for react – redux from all over the wide web.
    Thank you so much for such a masterpiece tutorial. would help me, if you have some reference for saga as well.

  15. Hey, this guide really helped me. Thanks for all your hard work.

    Wanted to let you know about one small typo. In the section: “React Redux tutorial: App component and Redux store”, there is a typo in the imports of the `./js/index.js`.

    should be:

    import store from “./store/index”;
    import App from “./components/App”;

    not:

    import store from “../js/store/index”;
    import App from “../js/components/App”;

  16. Hi Valentino and thanks so much for the tutorial.

    This may be a really dumb mistake, but I keep getting and error when I try to dispatch addArticle. Can’t figure out where exactly I am not importing it:

    store.dispatch( addArticle({ name: ‘React Redux Tutorial for Beginners’, id: 1 }) )
    VM13714:1 Uncaught TypeError: addArticle is not a function
    at :1:17

    Thanks again,
    Gal

    1. this is very embarrassing i am sorry. i forgot to save src/js/actions/index.js… 🙂

      please remove my comment and thanks again for the guide!!

  17. Very nice! I am an experienced developer but I started away from redux because of all the jargons. This was very simple. I can use redux now ?

  18. Very clear and well written tutorial! Impressive! I had no problem following the concepts or the code even though I have never used redux or react before.

  19. Thanks for your simple tutorial about React/Redux for beginners.
    I am a developer who is trying to learn react and redux and has problems while understanding tutorials from several websites.
    After reading your tutorial, it gets better to understanding the relationships between reducer,action and state.
    Also how to glue react and redux.
    Thanks very much.

  20. Thanks for this tutorial. It is so amazing, I have been confused about Redux until reading this. Thank you very much and wish you the best.

  21. You published an excellent guide for us. Even as React beginner I was capable to understand and reproduce all steps with the expected results.
    Thank you very much from Colombia.

  22. Joining the sentiment of the rest of people here:

    THANKS Valentino for taking the time to write and share this super comprehensive tutorial with a great simple (and very common) scenario.

    I now have a clearer idea of Redux and how it actually works.

    Grazzie mille!

  23. My bad, i use combineReducers and i forgot to add initialState. Please ignore my comment above. Thanks for nice tutorial.

  24. Excellent tutorial, thanks so much.
    Everything in your Redux and React tutorial worked great and your explanations are excellent.

    One minor issue I had was getting your bootstrap styles to work. I added

    // src/js/index.js
    import ‘bootstrap/dist/css/bootstrap.min.css’;

    Then:
    npm i bootstrap –save-dev

    That worked for me. Any other suggestions?

    thanks,
    David

  25. For some reason, I had this unjustified fear associated with learning redux. This tutorial is great and not a bit overwhelming. Thanks for taking the time to write this tutorial, Valentino!

  26. This article is really awesome. This is meant for those who just started with Redux. Even I had a lot of fear with Redux. But this article really simplifies everything.
    I read this article once and everything was kind of clear.But it will take some time for sure.
    I really appreciate you for this !!!! Good luck

  27. I was about to rip my hair off when trying to understand Redux. This tutorial gave me back the hope. Everything makes so much more sense now. Thank you sooooo much!!!

  28. Hi Valentino,

    Thanks for the super-simple intro to Redux!

    Some questions/suggestions:
    1. Why is immutability of state such a big deal (any benefits)? It will be good if you can touch upon this.
    2. It will be more helpful if you can begin with an example WITHOUT Redux, as a stateful React component, pointing out the issues in it and then show how Redux solves it. Can you modify this tutorial to such a format? (I am just pointing to the fact that learning is more effective when you start from the familiar and then move to the unfamiliar)

    Thanks again for the great tutorial!!

  29. By far the best tutorial on React Redux out there. I wish book authors can also read and get some tips.
    It is simple, clear and not confusing. I can appreciate the simplicity and the way all is explained. Kudos!

  30. Wow, that was super helpful. I’m learning redux for a new app I will build and was confused for days where to even start. This took me a big step forward on my journey to the store.

    I was a little confused about the placement of Files during the tutorial. The github-repo saved me at the end.

    Thanks from Berlin,
    bob

  31. Thank you so much for the tutorial. I feel like I have a handle on React and Redux separately, but was unsure about React-Redux bindings. Would love to see more tutorials, maybe with thunks??

  32. Well, as a React/Redux beginner, i haven’t yet read the entire article that I can already say it’s an excellent resource! Concise,detailed, very well written with pertinent examples, all I need to learn efficiently how to use Redux. Thanks a lot! I’d give you a beer for that awesome tutorial 😛

  33. Nice Article , Explained in easy to understand flow. I was able to follow each step without difficulty . I would sub title the Blog as Redux Simplified .
    Thanks a lot for the blog.

  34. Hi VALENTINO,

    First of all, Thank you for such a helpful tutorial.
    I am following all the instructions in the tutorial and creating my first React + Redux app. When I fired npm start. It is giving me following error in browser console.

    ERROR in ./src/js/reducers/index.js
    Module build failed: SyntaxError: Unexpected token (8:15)

    6 | switch (action.type) {
    7 | case ADD_ARTICLE:
    > 8 | return { …state, articles: […state.articles, action.payload] };
    | ^
    9 | default:
    10 | return state;
    11 | }

    Can you please guide me to make it work ?

    Thanks
    Harpreet Gill

  35. I am Using combineReducers and getting “Uncaught TypeError: Cannot convert undefined or null to object”. Without the combineReducer it is working fine. Below is snippet of my Reducers.

    article.js:
    import { ADD_ARTICLE } from “../actiontypes/action-types”;

    const initialState = {
    articles: []
    };

    const articleReducer = (state = initialState, action) => {

    switch (action.type){
    case ADD_ARTICLE:
    return {…state, articles: […state.articles, action.payload] };
    default:
    return state;
    }
    };

    export default articleReducer;

    reducers\index.js

    import { combineReducers } from ‘redux’;
    import articleReducer from ‘./article’;

    export default combineReducers({
    articles : articleReducer
    });

  36. Absolutely wonderful! The best free Redux beginner’s guide i have found accross the web !

    Thanks a lot my friend 🙂

  37. Thank you for the tutorial. I was looking at many sites to grab the concept of Redux, however had difficulties to understand.
    Your tutorial is really easy and flawless. I really appreciate your work.

  38. Thanks Valentino Gagliardi,
    I found this interesting and you really save my life from those four folders: Actions , reducers, store, and constants. i read poeples code but never understand the concept because i dont know how they are link together but now ,i can chase my dream. Thanks man.

      1. But in addition, i would like if you can do a write up on two entry in webpack , am currently working on personal project like that, my reason for doing this is to learn more,like react, webpack and others.
        In this project i have two entry, and the reasons for those entries are because,
        my home page as different dependecy from others e.g like my styling(css), but since the output are bundled and release on a single page and ,i need to load my dependency differently so it wont conflict one another.
        this is my webpack.common.js

        // import path from ‘path’
        const path = require(‘path’)

        module.exports = {
        devServer: {
        contentBase: ‘./client/dist’
        },
        output: {
        filename: ‘[name].bundle.js’,
        path: path.resolve(__dirname, ‘dist’),
        publicPath: ‘/’
        },
        watch: true,
        watchOptions: {
        poll: 1000,
        aggregateTimeout: 1000,
        ignored: /node_modules/
        },
        resolve: {
        extensions: [‘.jsx’, ‘.js’]
        },
        module: {
        rules: [
        {
        test: /\.s?css$/,
        use: [‘style-loader’, ‘css-loader’, ‘sass-loader’]
        },
        {
        test: /\.(png|gif|jpe?g|svg)$/i,
        use: [‘file-loader’]
        },
        {
        test: /.jsx?$/,
        enforce: ‘pre’,
        use: [
        {
        loader: ‘babel-loader’
        }
        ],
        include: path.join(__dirname, ‘/client’)
        },
        {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: [‘file-loader’]
        }
        ]
        }
        }

        and my webpack.dev.js

        const merge = require(‘webpack-merge’)
        const path = require(‘path’)
        const webpack = require(‘webpack’)
        const HtmlWebpackPlugin = require(‘html-webpack-plugin’)
        const CleanWebpackPlugin = require(‘clean-webpack-plugin’)
        const common = require(‘./webpack.common.js’)
        // to allow Dotenv files
        const Dotenv = require(‘dotenv-webpack’)

        module.exports = merge(common, {
        mode: ‘development’,
        entry: {
        app: ‘./src/index.js’,
        print: ‘./client/index.jsx’
        },
        devtool: ‘cheap-eval-source-map’,
        devServer: {
        contentBase: ‘./dist’
        },
        plugins: [
        new CleanWebpackPlugin([‘dist’]),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
        new Dotenv({
        path: ‘./.env’,
        safe: false
        }),
        new HtmlWebpackPlugin({
        template: ‘./client/index.html’,
        filename: ‘index.html’,
        inject: ‘body’
        })
        ],
        optimization: {
        splitChunks: {
        cacheGroups: {
        commons: {
        name: ‘commons’,
        chunks: ‘initial’,
        minChunks: 2,
        minSize: 0
        }
        }
        },
        occurrenceOrder: true // To keep filename consistent between different modes (for example building only)
        },
        stats: {
        colors: true
        },
        output: {
        filename: ‘[name].bundle.js’,
        path: path.resolve(__dirname, ‘dist’),
        publicPath: ‘/’
        }
        })

        So ,please how do i go about it, thanks in anticipation.

  39. This hit the mark. I was looking at a chapter in React book that introduced Redux, but the author went too quickly into Redux. Now I will be able to go back and understand the more advanced example presented.

  40. Thanks for posting this tutorial. As a beginner, I found it very easy to understand the redux concepts.. kudos!

  41. Hello
    first of all, thanks for this amazing and simple tutorial !! found it through reddit .
    i wanna talk about the issue i encountered in the section : React Redux tutorial: Redux store methods.

    i followed the instructions quite well, thing is the first two steps (subscribe and dispatch work well in the console and i see a result as per indicated here..but when i want to verify the store by getState() , the array is empty despite the action being dispatched already..
    what’s the matter?.
    Would love to shed light on this point.
    Thank you again for this amazing ressource !

  42. Hi.

    its really great really got a basic concept to make redux work.
    but i have little confusion.
    you setup window.store = store or you pass a single store in provider to app what if you have more than one store?

  43. Hello Valentino,
    Wonderful tutorial. Your tutorial got me up and running with redux with minimum effort. I wasn’t able to get hold of redux until I read this piece of GOLD from you. Thanks a lot.

    I have a question. You did not use some thing like:
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

    or,

    import { composeWithDevTools } from “redux-devtools-extension”;
    const sagaMiddleware = createSagaMiddleware();
    const store = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(sagaMiddleware, thunk))
    );

    Then, how am I able to see redux changing states and other things in chrome redux extension ?

  44. Wouaw! So far this is the best tutorial I have found on react/redux for the beginners. It will require lot of practice to really get the differents concepts but everything is more clear in my head and seems simple now!
    Thank you very much!

  45. Great tutorial.
    I’ve looked through some of the guides to Redux but it still seemed very complex.
    Here topics are set very clearly and the way you put the knowledge in readers’ brains is amazing.
    Thank you very much.

  46. Thank you, Valentino!
    I’m really happy and touched when read this tutorial. Waited a long time to read one manual and awesome tutorial like this.

  47. Hi Valentino.

    Thank you so much for the tutorial. You really have made my life a lot better with this simple, easy to understand demonstration of how Redux works and how it plays with React. I cannot thank you enough!!

    Best regards,
    Ashvir

  48. Thanx a lot Valentino!
    It was my first time with Redux and I’ve found your tutorial very clear and well explained.

  49. Just amazing tutorial for react-redux. It is a real spoon feeding training I ever completed. It’s really helped me to brush up my react-redux knowledge. Thanks for this wonderful tutorial 😀

  50. I have found this React-Redux tutorial extremely useful, when i started with redux from the actual site, it sounded very complex but valentino has explained very well that it made me very easy and i learned in a day.
    Thanks valentino, for well stepped guide. Appreciate it !!!

  51. Thanks again! i rare post but this was such a great tutorial that wasn’t hello world but also wasn’t building a crazy web app either. Really straightforward and I could finally start to understand WHY we would use redux!

  52. Hi, Valentino. Let me tell you a little story.

    I had never had contact with React before. Until the company I work for decided to use it as our official front-end technology. So, I created a component from scratch managing the state the old way, with the setState method inside the component.

    Well, talking to some React enthusiasts, they told me I should take a look at Redux, for it had a better decentralized control of the state.

    So, I went to Google. I’ve read some articles, but yours is the best one ever. I mean, by far this is the best tutorial for React + Redux.

    Thanks so much for sharinh your knowledge.

    Best regards from Brazil.

    1. agreed. this is very to the point but not so rudimentary as hello world. I also REALLY appreciate that this is an original tutorial, and not something someone copied from somewhere and is a duplicate of other tutorials.

  53. Hi, Valentino,
    Thanks for the wonderful tutorial, i was struggling with the react redux from pas few months.
    but did not found any suitable tutorial.
    Thanks for making it simple. Now it is more clear.

    Thanks

  54. Thank’s very Much……….

    I was new to React, got My hands dirty with React and thought that’s all I need.
    Wait is that so?
    While working in My organization, came in front of REDUX, and was banging my head to learn REDUX, Nothing helped.
    But thank GOD, got this link.
    Now I can perform the Magic using REACT and REDUX…..

  55. Thanks Valentino! I’ve spent a lot of time (and money) trying to understand the principles you’ve just explained in this tutorial. Thanks a million!

  56. Wow! This article is amazing. I’m usually give up reading thing half way, but this article is simple and really easy to understand. Finally, I get to learn redux. Thank you so much.

  57. The only tutorial that actually helped me! I was about to give up attempting to understand how it works.
    Thanks A LOT!!! You’re awesome!

  58. OMG, thank you so much for such a simple tutorial, I’ve been struggling to pick up Redux for ages till I saw this. You’re awesome~!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.