Redux async logic and data fetching

How middleware works

Middleware, a extra step where async logics run.

Redux store itself don’t know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer, and notify the ui which needs to be updated. Any asynchronicity happen outside the store.

Redux middleware, on the other side, allow you to using async logics to interact with the store. Middleware has access to dispatch and getState, which means you could write async functions in the middleware, and still has the ability to interact with the redux store by dispatching actions.

There are three concepts: the middleware, the async function and dispatch function. In sync logic, store dispatch a action. However, in the async logics, store dispatch a async function which wraps a normal dispatch.

The store dispatches a async function, which takes dispatch and getState as arguments. In the async function, it execute the async logics and then dispatch an action as same as the normal dispatch process. It is a bit convoluted, check the code below for a deeper understanding.

There are loads of middleware for redux, the most common one is redux-thunk. As redux docs states: The word “thunk” is a programming term that means “a piece of code that does some delayed work”. The thunk middleware allows us to write functions that get dispatch and getState as arguments. The thunk functions can have any async logic inside, and that logic can dispatch actions and read store state as needed.

In short, thunk function takes dispatch and getState as arguments. It processes async logics first, then dispatch a action with the data coming from the async logics. Let’s write some code to explains this process.

How redux thunk works. Reference:




A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to make the fastest Promise library

React is all about composition


Servicenow x NodeJS Bridge Part #1

Update — Freyala Marketplace

When and how to use Vue 3.0 with Craft CMS

Vue + Craft

Search Engine Optimization for Single Page Applications

Tree Lists With Indeterminate Checkboxes in React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.

More from Medium

Unit test in React

React Code Architecture

Creating Reducers in Redux

Component Rendering in Reactjs(List rendering and conditional rendering)