What the Heck is a Thunk?
Tags: javascript, thunk, redux, webdev
Published: 2020-06-02 11:36:00

---
title: What the Heck is a Thunk?
published: true
description: Thunk is one of those programming terms that sounds intimidating, but many of us are actually familiar with and have used them.
tags: javascript, thunk, redux, webdev 
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/lrpxq7yp2ci6o0fof72y.png
canonical_url: https://typeofnan.dev/what-is-a-thunk/
---

<hr />

## If you enjoy this post, please give it a 💓, 🦄, or 🔖 and consider:

- signing up for [my free weekly dev newsletter](https://buttondown.email/devtuts)
- subscribing to [my free YouTube dev channel](https://www.youtube.com/c/devtutsco?sub_confirmation=1)

<hr />

"Thunk" is one of those programming terms that sounds intimidating, but many of us are actually familiar with and have used them. Let's first see how Wikipedia defines thunks[1]:

> In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine.

This offers a little help, but maybe is a little too abstract.

So, what is a thunk really? _It's simply a function returned from another function_. Let's look at a quick example in JavaScript:

```javascript
function delayedLogger(message, delay) {
  return function(logger) {
    setTimeout(function() {
      logger(message);
    }, delay);
  };
}
```

In this example, when we call the `delayedLogger` function, it returns a _thunk_. We can then pass that _thunk_ a `logger` parameter, which will be executed after the specified `delay`.

```javascript
const thunk = delayedLogger('See you in a bit', 2000);
thunk(console.log);
```

In this example, we'll see `"See you in a bit"` logged to the console after two seconds.

# Bonus: Use in Redux

If you're familiar with Redux, you likely know the concept of _action creators_: functions that return _action_ objects. The following is an example of an action creator that makes an action that adds a product to a shopping cart:

```javascript
function addToCart(product) {
  return {
    type: 'ADD_TO_CART',
    payload: product,
  };
}
```

It turns out that we need a little more flexibility with our action creators: we need to be able to _dispatch_ an action asynchronously: often after we perform a _fetch_ request to save or load data from an API. We can solve this issue by using `redux-thunk`, a Redux middleware that allows us to return _thunks_ from action creators [2].

Let's mock up what this would look like. We'll load a list of products from an API and then _dispatch_ an action with those loaded products.

```javascript
function loadProducts() {
  // Return a thunk
  return function(dispatch) {
    fetch('some-product-api-url')
      .then(res => res.json())
      .then(data => {
        dispatch({
          type: 'ADD_PRODUCTS',
          payload: data.products,
        });
      });
  };
}
```

And there we have it: A more practical application of the `thunk` concept!

<hr />

## If you enjoy this post, please give it a 💓, 🦄, or 🔖 and consider:

- signing up for [my free weekly dev newsletter](https://buttondown.email/devtuts)
- subscribing to [my free YouTube dev channel](https://www.youtube.com/c/devtutsco?sub_confirmation=1)

<hr />

References:

1. [Wikipedia: Thunk](https://en.wikipedia.org/wiki/Thunk)
2. [redux-thunk](https://github.com/reduxjs/redux-thunk)