Redux Thunk is a middleware for Redux that allows you to write asynchronous logic (like API calls) inside your action creators.
Normally, Redux actions must return a plain object. With Redux Thunk, you can return a function instead of an object — and that function can dispatch actions later, after an async task finishes.
🧠 Why We Use Redux Thunk:
- To handle async operations (e.g., API requests).
- To dispatch multiple actions — before and after an async call.
- To keep components clean by moving logic into action creators.
🧾 Example without Thunk (only sync):
const increment = () => {
return { type: 'INCREMENT' };
};
🕒 Example with Redux Thunk (async):
const fetchUsers = () => {
return async (dispatch) => {
dispatch({ type: 'FETCH_USERS_REQUEST' });
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
dispatch({ type: 'FETCH_USERS_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_USERS_FAILURE', payload: error });
}
};
};
Here, the action returns a function instead of an object, and
dispatchis used inside that function.
⚡ How It Works:
- Redux receives the action (a function).
- Redux Thunk middleware intercepts it.
- Executes the function and dispatches other actions when ready.
- Reducers handle those actions as usual.
🧰 Installation:
npm install redux-thunk
Add to store:
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
✅ In short: Redux Thunk lets you write async logic (like fetching data) in your actions, making your components cleaner and Redux flow more powerful.