What in the world is THUNK, and why do you need to know about it?

Elena Weber
3 min readJul 22, 2021

Alright, let’s assume we’re working on an SPA (Single Line Application) using React JS and Redux JS and have come to the point when it’s time to work on async functions (for example, we need to make a fetch to our backend or update an already existing item).

But aren’t actions just objects? Simple objects containing its type and payload? — you might wonder, — And if so, how can we do anything or, even more than that, achieve the so much needed asynchronism with them?

By default, all the actions in Redux are dispatched sync, one-by-one at a time. Uh-oh! This is not what we want, we want same old asynchronism known to us since JavaScript. Help!

No panic. Meet the hero of the day — THUNK. This is a type of middleware (aka a function) that allows async requests and delayed tasks. Let’s install it:

yarn add redux-thunk

You should also import these into your index.js file otherwise nothing will work:

import { createStore, compose, applyMiddleware } from ‘redux’;

import thunk from ‘redux-thunk’;

THUNK must be wrapped into applyMiddleware() function and mentioned in creating store — in my case it looks like this:

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

let store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

Basically, THUNK’s work is to make action creators functions (remember, those that are not pure objects) digestible for our reducer. So, if an action creator returns an object, THUNK doesn’t do anything with it, it just lets it pass through directly to the corresponding reducer. But if an action creator returns a function, THUNK starts doing its magic: it executes the function by passing dispatch method (store method to update it) and getState method (retrieves current state) to it as arguments and only after that it passes it on. Remember that all the actions in our App go through this middleware, it’s like a filter for action creators functions. This is what’s going on under the hood, according to the official documentation.

Source: redux.js.org

Here is a piece of my code with a THUNK function:

THUNK function here is anonymous and is returned with dispatch method as a parameter (look at the second line). Let’s take a closer look: first we return a fetch request made to the dream’s id (inside we patch and stringify it), then we transform the server response into json format and after that we dispatch the updated dream inside a properly-formatted action object. This is exactly what we wanted — now our reducer and state will surely understand what we want from them. Thank you, THUNK’s magic!

--

--

Elena Weber

A former English teacher is now a Software Engineer exchanging human languages for computer ones :)