Vinay Kumar

Comprehending redux thunk

If your ReactJS application depends on API calls then there is a high probability of you making use of redux package with thunk middleware. Like me you would also have thought "what the heck is this thunk middleware?". Do not fret because at the end of this blog post I am confident that you will be like "Whoa! Thunk is no big deal ".

The most import point to keep in mind that whenever an action or action creator is dispatched, redux handles it synchronously to avoid race conditions. Now let's say there is a need to dispatch after certain condition is met and the condition is of async nature. Examples of such conditions are API calls, time out functions, promises etc. So how can we handle such scenarios? One of many possible ways is to make use of thunk as middleware in redux. By making use thunk, we have the freedom to dispatch either plain object or function.

Let's have a look at the below actions.js file

From react container or component we can dispatch plain object by calling this.props.dispatch(displayMessage('I was dispatched immediately.')) and API function(async nature) by calling this.props.dispatch(fetchDataFromAPI()). The fetchDataFromAPI() function is a higher order function just like connect() function available in react-redux package. If a function is dispatched then thunk will pass dispatch and getState methods as argument to the function(line 14 in action.js).

Hurray! That's all there is to thunk. To summarize in a single line, whenever redux encounters with async nature then you can make use thunk.

You can take a look at this sample application which makes use of setInterval function in redux.