Open In App

What is the use of Middleware Redux thunk ?

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Redux is a powerful state management library for JavaScript applications, particularly useful when working with frameworks like React. One of the key challenges in managing state in modern web applications is handling asynchronous operations such as API calls. This is where Redux Thunk, a middleware, comes into play. In this article, we will explore what Redux Thunk is, why it is essential, and how to use it effectively.

What is Middleware in Redux?

Before diving into Redux Thunk, it's important to understand the concept of middleware in Redux. Middleware in Redux is a way to extend the functionality of the Redux store. It provides a third-party extension point between dispatching an action and the moment it reaches the reducer. Middleware can be used for various tasks such as logging, crash reporting, performing asynchronous actions, and more.

What is Redux Thunk?

Redux Thunk is a middleware that allows you to write action creators that return a function instead of an action. This function can be used to delay the dispatch of an action or to dispatch actions only if a certain condition is met. It makes it possible to handle asynchronous operations inside action creators, which is crucial for tasks like fetching data from an API.

Why Use Redux Thunk?

In a typical Redux application, action creators return plain objects. This works well for synchronous operations, but it falls short for asynchronous tasks. For example, when you need to fetch data from an API, you can't wait for the API response synchronously in the action creator. Redux Thunk addresses this limitation by allowing action creators to return functions that can perform asynchronous operations.

Here are some key benefits of using Redux Thunk:

  • Asynchronous Actions: It simplifies the process of handling asynchronous actions, such as API requests.
  • Conditional Dispatch: It allows actions to be dispatched conditionally, depending on the application's current state or the result of previous operations.
  • Complex Action Sequences: It enables complex sequences of actions to be dispatched in a controlled manner, ensuring better flow and error handling.

Redux Thunk is a middleware that allows you to return functions instead of plain objects from Redux actions. While standard Redux only permits simple, synchronous updates, Thunk extends this capability by letting you incorporate complex logic and asynchronous operations. The middleware doesn't interfere until an action returns a function, known as a "thunk function." This function receives two arguments:

  • dispatch: It is a method used to dispatch actions, that can be received by reducers. 
  • getState: It gives access to store inside the thunk function.

A thunk function may contain any arbitrary logic, sync, or async, and can call dispatch or getState at any time. Before moving any further let's understand the difference between the flow of redux with and without thunk.

Redux flow without thunk : 

Redux Flow with Thunk: 

Steps to Setup of Redux with Thunk

Step 1: To set up redux with thunk, we will start by creating a react application, and install all the required dependencies. Run the following command to create a new react application.

npx create-react-app myapp

Step 2: Open your project in a code editor and install all the required packages: redux, react-redux & redux-thunk.

npm install redux react-redux redux-thunk

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"web-vitals": "^2.1.4"
}

Now we'll create some actions and reducers to interact with the store based on those actions. 

We'll create two actions, deleteData is a normal action creator, it doesn't include any complex or async logic hence thunk will not interfere in its execution. The addData action creator contains async logic, hence we return a function (thunk function) that calls dispatch when data is fetched from the API. (For this tutorial we are using JSONPlaceholderAPI you can learn more about it here.) Then in the app.js file we add buttons to dispatch the actions and display the fetched data.

JavaScript
// action.js

// This is a synchronous action, hence
// thunk will not interfere.
export const deleteData = ()=>{
    return ({
        type : 'DELETE_DATA'
    })
}

// This function includes some async logic,
// hence we can dispatch action manually
export const addData  = ()=>{

    // Thunk Function
    return async (dispatch,getState)=>{

        // Fetching results from an API : asynchronous action
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/todos/1');
        const data = await response.json();

        // Dispatching the action when async
        // action has completed.
        dispatch({
            type : 'ADD_DATA',
            payload : data
        });
    }
}

Here we'll create reducers to update the state based on those actions, and export the reducers to create a state. 

JavaScript
// reducer.js

const { combineReducers } = require("redux");

const INITAL_STATE  = {
    todo : null
}

const dataReducer = (state=INITAL_STATE, action)=>{
    switch(action.type) {
        case 'ADD_DATA' : return {...state, todo : action.payload};
        case 'DELETE_DATE' : return INITAL_STATE;
        default : return state;
    }
}

const reducers = combineReducers({
    data : dataReducer
})

export default reducers

We will first cleanup some boilerplate code and then create a store with middleware thunk. Provider function centralizes the state in our whole application.

JavaScript
// index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

import { applyMiddleware, createStore } from "redux";
import reducers from "./reducers";
import thunk from "redux-thunk";
import { Provider } from "react-redux";


// Create store with the reducers and
// apply thunk as a middleware
const store = createStore(reducers, applyMiddleware(thunk));

const root = ReactDOM.createRoot(
    document.getElementById("root"));

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

We begin by importing all of the actions & hooks, then use the useDispatch hook to dispatch actions and the useSelector hook to access data in the store. We've added two buttons to call the handler functions handleAddData and handleDeleteData, which dispatch their respective actions.

JavaScript
// app.js

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addData, deleteData } from "./actions";
const App = () => {
  const dispatch = useDispatch();
  // Selects the state value from the store.
  const todo = useSelector((state) => state.data.todo);
  // Dispatches action to add the data
  const handleAddData = ()=>dispatch(addData());
  // Dispatches action to delete the data.
  const handleDeleteData = ()=>dispatch(deleteData());
  return (
    <div>
      <button onClick={handleAddData}>Add Data</button>
      <button onClick={handleDeleteData}>Delete Data</button>

      {todo && <div>{JSON.stringify(todo)}</div>}
    </div>
  );
};

export default App;

Output: 


Next Article

Similar Reads