What is ‘Thunk’? (Redux Middleware)

Yehuda Bortz
2 min readMay 6, 2021

My initial understanding of Thunk was way more complicated than it ever needed to be. Thunk in my mind was this magical piece of software that allowed you to make asynchronous API calls which would then update the state in your Redux store after that resolved.

While this is somewhat accurate that is not really what Thunk does. On the contrary. This is what your plain old JavaScript API calls do in conjunction with the actions that dispatch the data to your reducers which in turn update your Redux store.

What is Redux?

Redux put simply is just a big container for the data of your application. From this data we derive the state of an application. Examples of this may be information about the current user or the items in the current users shopping cart.

How does the Redux store get updated?

In Redux there are what’s called reducers. Simply put its one file (usually many files combined into one) that has a JavaScript switch statement. Each case in the switch statement does something different. But each case is uniquely identified by an action word. An example of this might be “ADD_USER”.

The switch statement will identify the case where the action is “ADD_USER” and update the state accordingly.

So why do we need Thunk?

With redux we like to define action files that handle the dispatching of these actions to our reducers. The action consists of two attributes. The action type to perform actions (i.e. “ADD_USER”) and the payload. The payload might be an item to add to the cart or a simple integer (anything really).

{ type: "ADD_USER", payload: user }

There is a small problem though. Let’s say we need to send a GET request to the API to get a user’s information before adding the user to the store. This is a very common occurrence. We have 2 options. We can either handle the fetch request in another file and wait for the request to resolve before sending it to the action that will then dispatch the data to the reducer, or we can use Thunk.

So what does Thunk do?

In Redux we can only pass an object into a dispatch. We cannot pass in a function. But with Thunk we can. In our action we can now create functions that can request the user from the API and then dispatch that data to the reducer, and all in the same action.

All Thunk does, is check if our action is a Function, if it is, then it returns that function and passes in dispatch to be used by the function. Otherwise it defaults to the regular action/dispatch procedure.

--

--

No responses yet