Redux & Redux Toolkit
/Advanced
Listener Middleware
Definition
An RTK middleware that lets you run 'side effects' (like API calls or analytics) in response to specific Redux actions being dispatched. It is a lightweight alternative to Redux Saga.
Explain Like I'm New
You tell the listener: 'Whenever ANY component dispatches the `login_success` action, I want you to wake up in the background and trigger this Google Analytics code.' The React components don't know it's happening.
Real World Example
Listening for the `logout` action. When it fires, the listener automatically runs code to clear out the user's `localStorage` and redirect them to the home page.
Common Use Cases
- •Reactive side effects
- •Analytics
- •Syncing Redux with LocalStorage
Interactive Example
import { createListenerMiddleware, isAnyOf } from '@reduxjs/toolkit'; import { login, logout } from './authSlice'; // 1. Create the listener const listenerMiddleware = createListenerMiddleware(); // 2. Define what it listens for listenerMiddleware.startListening({ // Listen for EITHER login or logout actions matcher: isAnyOf(login, logout), // 3. The side effect to run when it hears the action effect: async (action, listenerApi) => { // Grab the current state of the auth slice const authState = listenerApi.getState().auth; // Sync the Redux state to the browser's LocalStorage! localStorage.setItem('authData', JSON.stringify(authState)); } });
Interview Questions
basic
- Is the Listener Middleware built into RTK by default?
intermediate
- Why use Listener Middleware instead of just putting the side effect inside the Reducer?