Redux Thunk
Redux Thunk is middleware for Redux that allows working with async actions. Thunk allows actions to return functions instead of simple objects, making it possible to defer dispatch execution.
How Redux Thunk Works
Thunk allows action creator to return function instead of action object. This function can:
- Perform async operations
- Access store state via getState
- Dispatch other actions via dispatch
Redux Thunk Usage Example
// Without Thunk (sync action)
const increment = () => ({
type: 'INCREMENT'
});
// With Thunk (async action)
const incrementAsync = () => {
return (dispatch) => {
dispatch({ type: 'INCREMENT_REQUEST' });
setTimeout(() => {
dispatch({ type: 'INCREMENT_SUCCESS' });
}, 1000);
};
};
// Example with API request
const fetchUser = (userId) => {
return async (dispatch, getState) => {
try {
dispatch({ type: 'FETCH_USER_REQUEST' });
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
dispatch({
type: 'FETCH_USER_SUCCESS',
payload: data
});
} catch (error) {
dispatch({
type: 'FETCH_USER_ERROR',
error: error.message
});
}
};
};
Connecting Redux Thunk
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Redux Thunk Advantages:
Redux Thunk is especially useful for handling API requests and other async operations in Redux applications.