JavascriptFrontendWeb Design

why do we use Thunk in redux?

Thunk is a function that is executed in the redux store. It’s a simple function that takes an argument and returns a promise.

Thunk is used to make asynchronous calls, which are not always possible with pure functions. For instance, if we wanted to fetch data from an API and use it in our application, then Thunk would be utilized to return the data asynchronously without blocking the main thread of execution.

Thunk also helps us deal with side effects – in this case, we can pass a function that will handle any changes made by the API call and update our UI accordingly.

Adding

For adding redux-thunk package, you have to install it by <code>npm i redux-thunk</code>. after installing it you have to import <code>applyMiddleware</code> and include it in createStore parameter.

Example of Thunk in Store
We have mention App.js code where we are applying thunk and createing store for application from redux.

import React from 'react';
import ReactDom from 'react-dom';
import {Provider} from 'react-redux';
import {applyMiddleware, createStore} from redux
import thunk from 'redux-thunk';
import App from './App'
const store = createStore(rootReducer, {}, applyMiddleware(thunk))


ReactDom.render(
<provider store={store}>
<App>
</ provider>,
document.getElementByid('root');
);

 

Action with Axio request for Async request

export const addProduct = ({ title, userId }) => {
return dispatch => {
dispatch(addProductStarted());

axios
.post(`https://jsonplaceholder.typicode.com/todos`, {
title,
userId,
completed: false
})
.then(res => {
dispatch(addProductSuccess(res.data));
})
.catch(err => {
dispatch(addProductFailure(err.message));
});
};
};

As you can read above, thunk is use for async request like if you are calling a API. you can also pass error from thunk middleware.

Advantages of Thunk in redux:

– More concise, understandable, and maintainable code – Great for collaboration since the team can start working on different areas of the application without having to wait for others to finish their parts first

  • Easy to test
  • Performance gains from reusing thunks
  • React components can start using async actions without using the async/await syntax

 

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button