How to dispatch asynchronous actions using Redux Thunk?
Last Updated :
24 Apr, 2025
Asynchronous actions are very important in web development, particularly in tasks such as fetching data from API. Redux Thunk is a middleware using which you can write action creators that return a function instead of an object. This function can perform asynchronous operations and dispatch actions to try and catch blocks.
What is Redux Thunk?
Redux Thunk is like a co-worker for Redux, giving it the power to handle asynchronous actions. It’s that extra tool that allows your Redux store to deal with things like fetching data from a server or performing tasks that take some time. With Redux Thunk, your app can smoothly manage both synchronous and asynchronous operations.
Syntax of Redux Thunk:
export const fetchData = createAsyncThunk(
'data/fetchData',
async () => { } // runs when fetchData is dispatched
);
Approach to dispatch asynchronous actions using Redux Thunk
The approach is very simple. We will use the `createAsyncThunk` function provided by Redux Toolkit to create asynchronous action creators. This function will wrap an asynchronous function that will run when the parent function is dispatched.
Steps to Create React App and Installing Required Modules
Step 1: Create a new React JS app and enter into the directory by running the following commands
npx create-react-app my-app
cd my-app
Step 2: Install the required modules
npm install @reduxjs/toolkit react-redux redux-thunk
Project Structure:

Dependencies: The updated package.json file should look like this.
"dependencies": {
"@reduxjs/toolkit": "^2.2.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"redux-thunk": "^3.1.0",
"web-vitals": "^2.1.4"
}
Example: Here is an working example of the approach. We have created and updated the following files.
CSS
/* App.css */
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.fetch-button {
padding: 10px 20px;
margin-bottom: 20px;
font-size: 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.fetch-button:hover {
background-color: #0056b3;
}
.loading {
margin-top: 20px;
font-size: 60px;
}
.todos-list {
list-style: none;
padding: 0;
}
.todos-list li {
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
JavaScript
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
JavaScript
// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchTodos } from './redux/userSlice';
import './App.css';
function App() {
const dispatch = useDispatch();
const todos = useSelector((state) => state.todos);
return (
<div className="container">
<h1>Todos</h1>
<button className="fetch-button" onClick={
() => dispatch(fetchTodos())
}>
Fetch Todos</button>
{todos.loading && <p className="loading">Loading...</p>}
<ul className="todos-list">
{todos.data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
);
}
export default App;
JavaScript
// userSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchTodos = createAsyncThunk(
'todos/fetchTodos',
async () => {
try {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos');
if (!response.ok) {
throw new Error('Failed to fetch todos');
}
const todos = await response.json();
return todos;
} catch (error) {
throw new Error('Error fetching todos');
}
}
);
const todosSlice = createSlice({
name: 'todos',
initialState: {
data: [],
loading: false,
error: null,
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchTodos.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchTodos.fulfilled, (state, action) => {
state.loading = false;
state.data = action.payload;
})
.addCase(fetchTodos.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export default todosSlice.reducer;
JavaScript
// store.js
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from './userSlice';
const store = configureStore({
reducer: {
todos: todosReducer,
},
});
export default store;
Output: Run the server by running the following command
npm start
output
Similar Reads
Handling asynchronous actions with Redux Thunk
Managing asynchronous actions using Redux Thunk is a prevalent approach in Redux-based applications. Redux Thunk serves as middleware, enabling the creation of action creators that return functions rather than action objects. These functions can execute asynchronous tasks, like fetching data from an
4 min read
How to fetch data from APIs using Asynchronous await in ReactJS ?
Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo
3 min read
How to handle more action using redux ?
In Redux, actions are the JavaScript object which has information. Having multiple actions will need multiple action creators. These actions should be unique in redux. Especially, the type of action must be defined properly to identify that. We will take the example of to-do list actions. There are
4 min read
How to connect the components using Connect() in React Redux
In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using
3 min read
Difference Between Synchronous and Asynchronous Action Creators
In web development, Redux has become very popular for managing application state. Action creators play an important role in Redux, which helps the dispatching of actions to update the state. In this article, we will understand the difference between synchronous and asynchronous action creators.What
4 min read
Create a To-Do List App using React Redux
A To-Do list allows users to manage their tasks by adding, removing, and toggling the completion status for each added item. It emphasizes a clean architecture, with Redux state management and React interface rendering. Todo AppPrerequisites Node.jsReactReact-ReduxApproachCreate a new React project
3 min read
What are Action's creators in React Redux?
In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects.Action C
4 min read
How to Handle Forms in Redux Applications?
Handling forms in Redux applications involves managing form data in the Redux store and synchronizing it with the UI. By centralizing the form state in the Redux store, you can easily manage form data, handle form submissions, and maintain consistency across components. We will discuss a different a
5 min read
How to test React-Redux applications?
Testing React-Redux applications is crucial to ensure their functionality, reliability, and maintainability. As we know, the React-Redux application involves complex interactions between components and Redux state management, testing helps us to identify and prevent bugs, regressions, and performanc
10 min read
How can you optimize the performance of React-Redux applications?
Performance optimization in React-Redux involves improving the speed, efficiency, and responsiveness of applications by minimizing rendering times, reducing unnecessary re-renders, and optimizing data fetching and processing. By implementing optimization techniques, you can enhance the overall user
5 min read