DEV Community

builtbyjosh
builtbyjosh

Posted on

Redux Thunk

What is thunk? Thunk is one of the most common redux middleware packages for redux. What is middleware? Middleware has the ability to stop, modify, or otherwise mess around with actions. There are plenty of middleware packages available, and they are mostly used for dealing with async actions. That is where thunk comes into play!

It is mainly used for asynchronous data calls. You can delay the dispatch of an action until all of the desired data is retrieved or the returned function has been called and completed its task. An example would be making a GET request to an outside API, you will need to wait for all of the data to be returned before you dispatch the action associated with the request. Or else you will run into errors when trying to render your components.
Normally, action creators can only return objects. But with redux-thunk, they can return functions to the action creators. When a normal object is passed to the action creator, it will carry out the action right away. But if a function, ie a fetch to an outside API, is called, thunk will call that function asynchronously. Once the promise is resolved, thunk will pass the returned value to the action creator.

The main way to use redux-thunk is to apply it when your redux store is created. You will first need to install redux-thunk to your app by using the command:

npm install --save redux-thunk
Enter fullscreen mode Exit fullscreen mode

Once thunk is installed, you will need to import it into your app. As well as importing createStore and applyMiddleware from the redux package.

import { createStore, applyMiddleware } from 'redux
import thunk from 'redux-thunk';
Enter fullscreen mode Exit fullscreen mode

Once all of these files are imported into your component, you will be able to create your redux store using:

const store = createStore(
    yourReducer,
    applyMiddleware(thunk)
):
Enter fullscreen mode Exit fullscreen mode

Make sure to import your reducer to the file where you are creating your store. This will connect your store and reducers to thunk and allow you to make asynchronous calls.

Top comments (0)