Photo by AltumCode on Unsplash

This article briefs about middlewares in React and how redux-thunk works.

What is a Middleware?

Middlewares are plain JavaScript functions.

They get executed with every action we dispatch.

Before we get into middlewares, the basic algorithm of the redux is

  1. Action creators produce an action.

Action creators are the ideal place to make the network requests. In the action creators we make the network requests and return action object with network response in the “payload” property.

To begin with, lets start looking into the types of action creators we have in redux.

  1. Synchronous Action Creators: These action creators return action objects with data. (ready to go!)

Redux thunk

Redux thunk is a middleware helps us to make network requests in a redux application.

Action creators can return either an object or a function. If it returns an object, it still requires the “Type” property. If it returns a fuction, redux-thunk will call call the function automatically for us!

With the function we return, we receive two important arguments “dispatch” and “getState”.

“getState” can be invoked on the redux store and it helps us to retrive all the state inside our global store of the application.

Steps inside Redux-Thunk,

  1. Redux-Thunk will invoke our function with the two arguments “dispatch” and “getState”.

NOTE: With redux-thunk, we can manually dispatch an action at some point in future.

With the redux-thunk in picture, the application flow will be of,

  1. Action Creators produce an action.

Front-end developer.