Redux-Thunk explained “Simply”

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!

In React, you dispatch an action creator fetchProducts .

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.

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 :)

Front-end web developer and graduate student from Microverse.