DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

Understanding redux-thunk in 5 minutes

Assuming you already understand Redux, and how we can dispatch an action, then it is easy to understand redux-thunk.

We know we can dispatch an action, which is just an object:

{ type: "GOT_DATA", data: data }
Enter fullscreen mode Exit fullscreen mode

Now, instead of

dispatch({ type: "GOT_DATA", data: data });
Enter fullscreen mode Exit fullscreen mode

What if we don't have data yet, and we can view it as asynchronous or a future value? What if we say, we can let you dispatch a function that will do something, and your function should just eventually dispatch an action object with that data when you have it?

That's redux-thunk: dispatch a function, and in our case, dispatch a function that will start something asynchronous and dispatch the action object when ready:

dispatch(function() {
  fetch(' .. ')
    .then(response => response.json())
    .then(data => dispatch({ type: "GOT_DATA", data: data }))
    .catch(err => dispatch({ type: "CANNOT_GET_DATA", error: err }));
});

Enter fullscreen mode Exit fullscreen mode

That's it. Now you already know how redux-thunk works.

To understand what the "thunk" part is, it is: when we have actionCreator() that returns an action object in the past, now in this case, this actionCreator() returns the function we have above instead.

Now, this actionCreator() is like a wrapper that returns a function, and in 1960, that wrapper is called a thunk in the ALGOL community, like something that has already been "think" (thunk) or "thought" of. So when you dispatch a function, that function is not a thunk. The wrapper that creates the function for you to dispatch, is the thunk.

Note that in redux-thunk, this wrapper actually returns a function that takes dispatch as a parameter, so that when you call dispatch at last, you are using this dispatch.

That may seem complicated: a function that returns a function that takes dispatch, and eventually will call dispatch(someActionObject), but a simple way is just to think of: instead of dispatching an action object, dispatch a function that does something and eventually will dispatch the action object.

Top comments (0)