Where and When to Fetch Data With Redux

By Dave Ceddia  — updated Comment

If a component needs data in order to render, and you want to fetch that data with Redux and keep it in the Redux store, when is the best time to make that API call?

tl;dr – Kick off the action in the componentDidMount lifecycle hook

Making API Calls with Redux

Let’s imagine you want to display a list of products. You’ve got a backend API that answers to GET /products, so you create a Redux action to do the fetching:

export function fetchProducts() {
  return dispatch => {
    return fetch("/products")
      .then(res => res.json())
      .then(json => {
        return json.products;
      .catch(error => dispatch(fetchProductsFailure(error)));

// Handle HTTP errors since fetch won't.
function handleErrors(response) {
  if (!response.ok) {
    throw Error(response.statusText);
  return response;

Side note: fetch() does not throw for HTTP errors like 404s. This is really confusing if you’re used to something like axios. Read here for more about fetch and error handling.

Redux actions that fetch data usually come in triplets: BEGIN, SUCCESS, FAILURE. This isn’t a requirement, it’s just a convention.

Before you start the API call, you dispatch the BEGIN action.

Then after the call succeeds, you dispatch SUCCESS with the data. If it failed instead, you dispatch FAILURE with the error.

This structure is nice because it gives you hooks to keep track of what’s happening – say, by setting a “loading” flag true in response to the BEGIN action, and then false after SUCCESS or ERROR. Here’s what those actions look like:


export const fetchProductsBegin = () => ({

export const fetchProductsSuccess = products => ({
  payload: { products }

export const fetchProductsError = error => ({
  payload: { error }

And then we’ll have the reducer save the products into the Redux store when it receives the FETCH_PRODUCTS_SUCCESS action. It’ll also set a loading flag to true when the fetch begins, and false when it finishes or fails.

import {
} from './productActions';

const initialState = {
  items: [],
  loading: false,
  error: null

export default function productReducer(state = initialState, action) {
  switch(action.type) {
      // Mark the state as "loading" so we can show a spinner or something
      // Also, reset any errors. We're starting fresh.
      return {
        loading: true,
        error: null

      // All done: set loading "false".
      // Also, replace the items with the ones from the server
      return {
        loading: false,
        items: action.payload.products

      // The request failed, but it did stop, so set loading to "false".
      // Save the error, and we can display it somewhere
      // Since it failed, we don't have items to display anymore, so set it empty.
      // This is up to you and your app though: maybe you want to keep the items
      // around! Do whatever seems right.
      return {
        loading: false,
        error: action.payload.error,
        items: []

      // ALWAYS have a default case in a reducer
      return state;

Finally, we just need to pass the products into a ProductList component that will display them, and also be responsible for kicking off the data fetching.

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

class ProductList extends React.Component {
  componentDidMount() {

  render() {
    const { error, loading, products } = this.props;
    if (error) {
      return <div>Error! {error.message}</div>;

    if (loading) {
      return <div>Loading...</div>;

    return (
        {products.map(product =>
          <li key={product.id}>{product.name}</li>

const mapStateToProps = state => ({
  products: state.products.items,
  loading: state.products.loading,
  error: state.products.error

export default connect(mapStateToProps)(ProductList);

Error Handling in Redux

The error handling here is pretty light, but the basic structure will be the same for most actions that make API calls. The general idea is:

  1. Dispatch an ERROR action when the call fails
  2. Handle that ERROR action in the reducer by setting some kind of flag and/or saving the error message.
  3. Pass the error flag and the message (if you have one) into components that need to handle errors, and condtionally render the error however you see fit.

But It Will Render Twice!

This is a really common concern. And yes, it will render more than once.

It will render in an empty state, then re-render in a loading state, and then re-render again with products to show. The horror! 3 renders! (you could get it down to 2 if you skip straight to the “loading” state)

You may be worried about “unnecessary” renders because of performance, but don’t be: single renders are very fast. If you’re working on an app where they are slow enough to notice, do some profiling and figure out why that’s the case.

Think of it this way: the app needs to show something when there are no products, or when they’re loading, or when there’s an error. You probably don’t want to just show a blank screen until the data is ready. This gives you an easy opportunity to make those decisions.

But The Component Shouldn’t Have to Fetch!

From an architecture standpoint, it would be nicer if there was a parent “thing” (component or function or router or whatever) that automatically fetched data before it loaded the components. Then components could be blissfully unaware of any dirty API nonsense; they could simply wait around to be handed data on a silver platter. What a life!

There are ways to fix this, but as with everything, there are tradeoffs. Magic data loaders are magic (harder to debug, harder to remember how/when/why they work). They might require more code instead of less.

Many Ways To Skin This Cat

There are many many ways to factor this code. There is no “best way,” because these things exist on a spectrum, and because the “best” for one use case may be the “worst” for another.

“Fetch the data in componentDidMount” is not the one true way, but it’s simple, and it gets the job done.

If you don’t like the idea of doing it this way, though, here are some things you could try:

Like I said, there are a lot of ways to do this :)

Action Steps

Try implementing this yourself! Practice is the best way to learn.

If you don’t have your own backend server, just use Reddit – their URLs will return JSON if you append “.json” to the end, e.g. www.reddit.com/r/reactjs.json.

Make a tiny React + Redux app that displays the posts from /r/reactjs.

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.
— John Lyon-Smith
comments powered by Disqus