Redux-Thunk explained “Simply”

Abdo Amin
2 min readAug 24, 2021

--

Hello :)

This is a quicky article.

I am going to explain what is middleware in Redux and what is Thunk.

If you don’t understand Redux well enough, I suggest that you read my article on Redux.

What is middleware?

Reducers in Redux must be always pure functions, which means you CAN’T do any side-effects (e.g fetch API).

Now, this is a problem because you can’t have an “async” logic in your application which means for example you can’t fetch data from an API.

Solution? Middlewares!

Middleware in Redux is a utility placed between the dispatch method and the reducer.

Middleware visualization.

What is Thunk?

Thunk basically is a way to write async functions in Redux.

Let’s break it down!

1- Dispatch the action creator

In React, you dispatch an action creator fetchProducts .

2- A function (action creator) that creates functions 🤔

fetchProducts is an action creator that takes dispatch as an argument and returns a new function, inside of this function you can do any async operation.

After the async logic is done, the new function dispatch a new action creator productSuccess with the data returned from the fetch.

3- An action creator that actually returns an action 🙃

productSuccess is an action creator that returns an action along with the returned data as a payload.

This is the magic of middleware, It is almost like an extension or add-on!

Thank you for reading :)

--

--

Abdo Amin

I love React and anything that has JavaScript and frontend in it.