DEV Community

javinpaul
javinpaul

Posted on

Understanding Redux Thunk in React.js with Example

If you are a react developer, then you must have used state in your project. There is no react project without a state. The state is defined as an instance of a component. It is an object that controls the behavior of a component.

In this article, we will learn about Redux Thunk, a useful concept when it comes to statement in React.js. State management is one of the most important concepts in react.

This is part 3 of my React for Java developer series and in the past two articles we have been focusing on statement management in React and we have seen that how to use manage state using Redux and useState hooks. If you haven't checked them yet then you can check them now to learn React core concepts better.

React has in-built support for the state. But as the application grows, managing the state using the in-built features becomes difficult.

So in bigger applications, third-party libraries are used to manage the global state. Redux is the most popular and commonly used state management library. But the focus of this article is not redux. It is "redux-thunk".

Redux-thunk is used to manage the state of a react application. In this article, we will discuss what redux-thunk is and why we should use it.

If you're a complete beginner on React then don't worry, have also shared both the best React courses and books, as well as The React Developer RoadMap, which provides all the tools, libraries, and resources you need to become a proficient React Developer. You can go through those resources to learn React.js from scratch.

Async function middleware

A basic rule of writing reducers in React + Redux application is that it should not have side effects. A side effect is something that can change something which is not in the scope of the function. Making HTTP calls is one example of the side effects.

HTTP calls are a side effect but it is an essential part of a web application. We cannot make HTTP calls in a reducer but we can create middleware for it. To handle such situations, we need to create async function middlewares.

We can write async function middleware but react already provides them. Redux thunk is nothing but async function middleware.

What is redux thunk? Example tutorial

What is Redux thunk?

Basically, redux-thunk lets us write functions that can handle async logic such as HTTP calls. In such a function, we can dispatch an action and also access the state of the application. But how? A thunk middleware has two arguments - dispatch and getState.

To use redux-thunk, it needs to be installed using the Node Package Manager (NPM).

npm install redux-thunk
Enter fullscreen mode Exit fullscreen mode

After installing, we need to import "thunkMiddleware" from "redux-thunk" in the store file. Remember, the store should have the ability to pass the thunk middleware to the dispatch function. For this, we need to use "applyMiddleware" like the following.

import { createStore, applyMiddleware } from 'redux';

import { composeWithDevTools } from 'redux-devtools-extension';

import thunkMiddleware from 'redux-thunk';

const enhancer = composeWithDevTools(applyMiddleware(thunkMiddleware));

const store = createStore(reducer, enhancer);

This is how we can apply "thunkMiddleware" to the store. Now let's see how we can write a thunk function.

export async function getData(dispatch, getState) {

const res = await client.get('/getdata')

    dispatch({ type: 'RES_DATA', payload: res.data })

}
Enter fullscreen mode Exit fullscreen mode

"getData" is a thunk middleware function. It has two parameters - dispatch and getState. In the last line of the function, dispatch is used to dispatch the required action.

So what happened here? The middleware function we created above is handling the asynchronous HTTP call that is providing the data.

If we do not have redux-thunk, then where should we write this logic? We cannot write it directly in the reducer and neither inside the action because they cannot have side effects. So we have redux-thunk middleware where we can write async logic.

Remember earlier we gave the ability to the store to pass the middleware function to the dispatch function? Observe the following line of code.

javascript
store.dispatch(getData);
`

When the above code is executed somewhere in the application, the "getData" function is invoked. At this point, no action is dispatched. So it is absolutely fine to make HTTP calls in the "getData" function.

When the call is made and a response is received, the "dispatch" function provided by redux-thunk can dispatch the required action. From here, the normal redux flow can continue to update the state.

So this is how redux-thunk is useful in a react application that is using Redux to manage the state. The thunk middleware is neither an action nor a reducer so it can have side effects. Moreover, it provides the dispatch and getState function that let us dispatch actions and access state respectively.

That's all about Redux Thunk. If you are going to use redux in your react application, then you should understand the working of redux-thunk. It is a very useful concept that will help you manage side effects efficiently. So go through this article and create your own react application with redux and implement redux-thunk in it to understand the concept more clearly.

Other React Tutorials and ResourcesYou May like to explore

Thanks for reading this article so far. If you like these free React framework courses, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P. S. - If you are a complete beginner on React and JavaScript then I also suggest you check out these free JavaScrpt courses first before jumping into React.js. It will save you a lot of time particularly when it comes to reading and understanding code. Once you have done that you can use these free React.js courses to start learning React from scratch.

Top comments (0)