Codementor Events

Step-By-Step: How to Add Redux Thunk to Your React & Redux Project

Published Dec 21, 2019Last updated Dec 30, 2020
Step-By-Step: How to Add Redux Thunk to Your React & Redux Project

Got no time? Clone the repo and get going!

git clone https://github.com/rajjeet/react-playbook
cd react-playbook/packages/redux-thunk
npm install
npm start

redux-thunk.gif

Quick Setup

Checkout of my previous articles for setup code:

Fun Fact

Thunk is the past tense of think

Redux thunk helps introduce asynchronous behaviour to your redux actions, such as API calls.

Step 1. Install redux-thunk

npm install redux-thunk

Step 2. Apply redux-thunk to Redux Middleware

/src/configure-store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
...
export const store = createStore(countReducer, applyMiddleware(thunk));

Step 3. Dispatch Function Instead of Object

Without redux-thunk, we are only allow to dispatch objects with a type property. With this middleware, we can return functions. Within the functions, we can do async calls (i.e. API calls) before or after we dispatch actions.

src/counter/container.js
const mapDispatchToProps = dispatch => {
  return {
    handleIncrementClick: () => dispatch(      
      innerDispatch => innerDispatch({ type: 'INCREMENT' })      
    ),
    handleDecrementClick: () => dispatch({ type: 'DECREMENT' })
  }
};

Notice how I changed handleIncrementClick that was previously returning just the plain object.

src/counter/container.js (before)
  ...
    handleIncrementClick: () => dispatch({ type: 'INCREMENT' })
  ...

Compare it to handleDecrementClick and see the difference.

Remarks

  • The code in the container looks ugly. You should refactor all the actions into a separate file specific to this container (actions.js). The functions can live anywhere.

    src/counter/actions.js
    export const incrementAsync = innerDispatch => innerDispatch({ type: 'INCREMENT' });
    
    src/counter/container.js
    import { incrementAsync } from './actions';
    ...
        handleIncrementClick: () => dispatch(incrementAsync),
    ...
    
  • No async call was made here to stay honest to the title, but you can easily add async code before or after dispatching actions. You can orchestrate the UI to show loading and complete states. Each dispatch would update the UI to reflect the state of the async action.

  • I made this article extremely simple to show the core effect introduced by thunk. For a more detailed example, see the documentation.

Discover and read more posts from Rajjeet Phull
get started