What is Thunk?
- The past tense of thought is thunk. Hahaha, 😁 Jokes apart.
- Your redux operations, such as API requests, can now exhibit asynchronous behavior thanks to redux-thunk.
- A middleware called [Redux Thunk](https://www.nimblechapps.com/services/react.js-development-company) enables you to call action creators that give back functions rather than action objects.
Redux Flow Without Thunk
Redux flow with Thunk
Step 1 - Installation and setup
Running the following command will install redux-thunk:
`
npm install redux-thunk
`
Step 2 - Implement redux-thunk to Redux Middleware
`
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
...
export const store = createStore(countReducer, applyMiddleware(thunk))
`
Step 3- Dispatch a Function rather than an Object
We can only dispatch objects with a type property without redux-thunk. We are able to return functions using this middleware. We can do async calls (that is, API calls) within the routines either before or after we dispatch actions.
src/count/container.js
`
const ABC = dispatch => {
return {
handleIncrClick: () => dispatch(
innerDispatch => innerDispatch({ type: 'INCREMENT' })
),
handleDecrClick: () => dispatch({ type: 'DECREMENT' })
}
};
`
All of the actions should be refactored into a separate file just for this container (actions.js). The operations may be located anywhere.
src/counter/actions.js
`
export const incrasync = innerDispatch => innerDispatch({ type: 'INCREMENT' })
`
src/count/container.js
`
import { incasync } from './actions';
...
handleIncrClick: () => dispatch(incrasync);
...
`
Why do we need redux-thunk?
It enables us to have redux operations return functions rather than objects. Simple synchronous updates can only be made by dispatching actions in plain redux, which does not support complicated logic inside action functions. This middleware broadens its functionality and enables you to create intricate logic that communicates with the store. If you are still confused, a top react js app development company can assist you in setting up redux thunk in ReactJS.