Using Middleware in Redux Applications

Tutorial 4 of 5

Introduction

Goal of this tutorial: This tutorial aims to guide you through the process of using middleware in Redux. By the end of this tutorial, you should have a clear understanding of what middleware is, its role in Redux, and how to use middleware tools such as redux-thunk and redux-saga.

What you will learn:
- How to use middleware in Redux applications.
- How to use Redux-thunk and Redux-saga middleware.

Prerequisites:
- Basic knowledge of JavaScript and Redux.
- Familiarity with ES6 syntax and concepts.

Step-by-Step Guide

In Redux, middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. Middleware can be used for logging, crash reporting, handling asynchronous actions, etc.

Redux-thunk and Redux-saga are two such middleware tools that let you handle async logic in Redux.

Redux Thunk

Redux-Thunk is a middleware that allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.

Redux Saga

Redux-Saga, on the other hand, is a middleware for managing side effects such as asynchronous things like data fetching and impure things like accessing the browser cache in Redux applications.

Code Examples

Using Redux Thunk

Here is a simple example of Redux Thunk in action:

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

// This is a reducer
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

// Create a Redux store holding the state of your app.
let store = createStore(counter, applyMiddleware(thunk));

// Now, you can dispatch async actions
store.dispatch((dispatch, getState) => {
  // async code here
  dispatch({ type: 'INCREMENT' });
});

In this code snippet, we first import the necessary libraries. We define a simple reducer function counter which increments or decrements the state based on the action type. Then, we create a Redux store with createStore function and apply the thunk middleware to it with applyMiddleware function. Finally, we dispatch an async action.

Using Redux Saga

Here is a simple example of Redux Saga in action:

import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';

// This is a reducer
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

// This is a saga
function* incrementAsync() {
  yield delay(1000);
  yield put({ type: 'INCREMENT' });
}

// Create a Redux store holding the state of your app.
let sagaMiddleware = createSagaMiddleware();
let store = createStore(counter, applyMiddleware(sagaMiddleware));

// Then run the saga
sagaMiddleware.run(incrementAsync);

In this code snippet, we first import the necessary libraries. We define a simple reducer function counter and a Saga incrementAsync which delays for 1 second and then dispatches an 'INCREMENT' action. Then, we create a Redux store with createStore function and apply the saga middleware to it with applyMiddleware function. Finally, we run the saga with sagaMiddleware.run().

Summary

In this tutorial, we've learned about middleware in Redux, and how to use the Redux-Thunk and Redux-Saga middleware. We've seen how Redux-Thunk allows us to dispatch async actions, and how Redux-Saga helps us manage side effects in our Redux applications.

Practice Exercises

  1. Exercise 1: Write a Redux application that uses middleware to log all actions and the state after they are dispatched.
  2. Exercise 2: Write a Redux application that uses Redux-Thunk middleware to handle async actions.
  3. Exercise 3: Write a Redux application that uses Redux-Saga middleware to manage side effects.

Additional Resources