Redux Thunk
Redux Thunk is a middleware for Redux that allows you to write action creators that return a function instead of an action. This function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions or to dispatch further asynchronous actions.
Syntax:
// Action creator using Redux Thunk
const fetchData = () => {
return (dispatch) => {
dispatch({ type: 'FETCH_REQUEST' });
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data }))
.catch(error => dispatch({ type: 'FETCH_FAILURE', payload: error }));
};
};
Features:
- Simple setup and integration with existing Redux applications.
- Well-suited for simpler use cases and smaller applications.
- Easier to understand for developers familiar with Redux.
Example:
// Reducer
const initialState = { data: [], loading: false, error: null };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_REQUEST':
return {
...state,
loading: true
};
case 'FETCH_SUCCESS':
return {
...state,
loading: false,
data: action.payload
};
case 'FETCH_FAILURE':
return {
...state,
loading: false,
error: action.payload
};
default:
return state;
}
};
// Redux store setup
const store = createStore(reducer, applyMiddleware(thunkMiddleware));
// Dispatching action
store.dispatch(fetchData());
Redux Thunk vs. Redux Saga: Choosing the Right Middleware
Redux, a predictable state container for JavaScript apps, is widely used in React applications for managing application state. Redux Thunk and Redux Saga are middleware libraries commonly employed with Redux for managing side effects such as asynchronous API calls, complex state transitions, and more. Both offer solutions for handling asynchronous actions, but they have different approaches and use cases.
Table of Content
- Redux Thunk
- Redux Saga
- Differences between Redux Thunk and Redux Saga middleware libraries
- Summary