Getting started with Redux Thunk

Oluwakeye John
October 03, 2020 · 1 min read

What is Redux Thunk?

Redux is a great library which allows us to maintain state better in out applications. By using middlewares, we are also able to extend redux with additional functionalities. According to the documentation, it provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. One of these middlewares is Redux Thunk.

“Redux Thunk is a middleware that allows us to write action creators that return a function instead of an action object.”

To recap, actions are JavaScript objects which carries information to update while action creators are are merely functions that returns an action object.

To update state in redux, we dispatch an action and these actions are plain objects. According to the docs, Without middleware, Redux store only supports synchronous data flow, which means by default, redux action creators doesn’t support asynchronous actions like fetching data from a remote API or DB.

Redux Thunk allows Redux to dispatch actions that are functions. That ability to dispatch functions gives us the ability to embed logic operations in out actions. The function can be asynchronous, can contain logic, or anything.

That function can be of any form, be it synchronous or asynchronous. When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function doesn’t need to be pure; it is thus allowed to have side effects, including executing asynchronous API calls.

This way, state and store logic can be abstracted out of your components. It also promotes reusablity of actions across components.

Installation

To use redux thunk, you can install it via yarn or npm.

npm install redux-thunk
# or
yarn add redux-thunk

To add a middleware to redux, you can import applyMiddlware from redux and pass it as a second parameter into createStore:

import { createStore, applyMiddleware } from "redux"
import myReducer from "./myreducer"
import thunk from "redux-thunk"

let store = createStore(myReducer, applyMiddleware(...thunk))
export { store }

With this, you have added support for redux thunk.

Usage

Here is an example that uses redux thunk:

import React from "react"
import { useDispatch } from "react-redux"

// app component
const App = () => {
  const dispatch = useDispatch()
  const handleClick = () => {
    dispatch(updateContent())
  }

  return (
    <div>
      <button onClick={handleClick}>Click to login</button>
    </div>
  )
}

// our action, using redux thunk
const updateContent = () => {
  //async function

  return async dispatch => {
    const resp = await fetch(`https://api-endpoint.domain`)
    const respJson = await resp.json()
    dispatch({
      // your action
    })
  }
}

In the above example, we are able to dispatch the updateContent function with the help of redux-thunk.

Summary

Using redux thunk has a lot of advantages:

  • Reusability of actions across components
  • It allows asynchronous and conditional dispatching
  • Components are independent of state logic
  • Actions can be nested into one another

You have a suggestion, or you want to know more about something I mentioned above? Then feel free to contact me