Skip to main content
TOPIC 3 OF 6 · 2 MIN READ

Middleware in Redux and Redux Thunk

Middleware in Redux intercepts actions before they reach the reducer. It is used to perform side effects like logging, API calls, or dispatching additional actions. Redux Thunk is a middleware that allows action creators to return functions instead of plain action objects.

Key concepts

Middleware

Intercepts actions before they reach the reducer. Used to perform side effects like logging, API calls, or dispatching additional actions.

Redux Thunk

A middleware that allows action creators to return a function (instead of an action). This function can perform asynchronous logic and dispatch actions based on results.

Step by step

Common Middleware:

  • Logging Middleware: Logs dispatched actions and updated state.
  • Thunk Middleware: Handles asynchronous logic like API calls.

Examples

Configure Store with Thunk:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const store = createStore(rootReducer, applyMiddleware(thunk));

Async Action Creator with Thunk:

const fetchUser = () => {
  return (dispatch) => {
    dispatch({ type: 'FETCH_USER_REQUEST' });

    fetch('https://jsonplaceholder.typicode.com/users/1')
      .then((response) => response.json())
      .then((user) => {
        dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
      })
      .catch((error) => {
        dispatch({ type: 'FETCH_USER_FAILURE', error });
      });
  };
};

// Dispatch async action
store.dispatch(fetchUser());

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus