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.
  2. The action gets fed to the dispatcher.
  3. The dispatcher sends it to the reducers.
  4. Reducers updates or modifies the State.

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!)
  2. Asynchronous Action Creators: These action creators requires some time to return the action objects because of the network requests.

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”.
  2. Inside our function, we wait for the network request to finish.
  3. Once we get the response, we use “dispatch” function to manually dispatch an action.

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

  1. Action Creators produce an action.
  2. The action gets fed to the dispatcher.
  3. Dispatcher forwards to .
  4. sends to the reducers.
  5. Reducers updates or modifies the State

Front-end developer.