Blog>
Snippets

Action Throttling Middleware

Demonstrate how to write Redux middleware that throttles actions to a permissible frequency, ensuring that synchronization does not overwhelm the network or devices.
const createThrottlingMiddleware = (delay) => {
  // Hold last execution timestamps for actions
  const timestamps = {};

  // Middleware function
  return store => next => action => {
    const time = Date.now();
    const lastExecution = timestamps[action.type] || 0;
    // Check if the action can be dispatched
    if (time - lastExecution >= delay) {
      timestamps[action.type] = time;
      return next(action);
    }
  };
};

// Apply the middleware that throttles actions with a 5000 ms delay
const throttleMiddleware = createThrottlingMiddleware(5000);

// Apply middleware to the Redux store
const applyMiddleware = Redux.applyMiddleware;
const createStore = Redux.createStore;
const rootReducer = (state = {}, action) => state;
// Create Redux store with throttleMiddleware
const store = createStore(
  rootReducer,
  applyMiddleware(throttleMiddleware)
);
This code creates a middleware function 'createThrottlingMiddleware' that accepts a 'delay' parameter. It then throttles actions based on their type, ensuring that the same action type cannot be dispatched more frequently than the specified delay. A throttled middleware is created with a 5000 ms delay and applied to the Redux store.