Redux thunk Middleware Everything explain 2025
Redux Thunk Middleware Explained 2025
Redux Thunk is a middleware that allows you to write action creators that return a function instead of an action.
This is useful for handling asynchronous logic like API calls in Redux.
Why Do We Need Thunk?
- Redux actions are synchronous by default
- APIs and side effects are asynchronous
- Thunk lets us handle async operations inside action creators
Installation
npm install redux-thunk
How to Setup Redux Thunk
import { legacy_createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const store = legacy_createStore(rootReducer, applyMiddleware(thunk));
Async Action Example
Here's how to fetch data from an API using Thunk:
// actions/userActions.js
export const fetchUsers = () => {
return async (dispatch) => {
dispatch({ type: "FETCH_USERS_REQUEST" });
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
dispatch({ type: "FETCH_USERS_SUCCESS", payload: data });
} catch (error) {
dispatch({ type: "FETCH_USERS_FAILURE", payload: error.message });
}
};
};
Reducer Example
// reducers/userReducer.js
const initialState = {
loading: false,
users: [],
error: ""
};
const userReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_USERS_REQUEST":
return { ...state, loading: true };
case "FETCH_USERS_SUCCESS":
return { loading: false, users: action.payload, error: "" };
case "FETCH_USERS_FAILURE":
return { loading: false, users: [], error: action.payload };
default:
return state;
}
};
export default userReducer;
Using in Component
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchUsers } from "./redux/actions/userActions";
function UserList() {
const dispatch = useDispatch();
const { users, loading, error } = useSelector(state => state.users);
useEffect(() => {
dispatch(fetchUsers());
}, [dispatch]);
return (
{loading ? "Loading..." : error ? error : users.map(user => {user.name}
)}
);
}
Benefits of Redux Thunk
- Handles complex async logic like API calls
- Can dispatch multiple actions (request, success, failure)
- Keeps UI responsive and state predictable
Redux Thunk is essential for making Redux work seamlessly with real-world APIs.