Blog>
Snippets

Debouncing Middleware for Redux Actions

Implement a debouncing middleware to prevent rapidly-fired consecutive identical actions in Redux v5.0.0.
const debounceMiddleware = ({ dispatch }) => {
  let timerId = null;
  const debouncedDispatch = action => {
    if (timerId) clearTimeout(timerId);
    timerId = setTimeout(() => dispatch(action), 500); // Set a 500ms debounce time
  };
  return next => action => {
    if (action.meta && action.meta.debounce) {
      debouncedDispatch(action);
    } else {
      return next(action);
    }
  };
};

export default debounceMiddleware;
This JavaScript code creates a Redux middleware named `debounceMiddleware`. It uses a closure to hold a `timerId` variable, which is used to track the timeout set for debouncing. The `debouncedDispatch` function resets the timer and dispatches the action after a debounce period of 500ms. The middleware checks if an action has a `meta.debounce` property, and if it does, it uses the debounced dispatch. Otherwise, it passes the action to the next middleware.
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import debounceMiddleware from './debounceMiddleware';

const store = createStore(
  rootReducer,
  applyMiddleware(
    debounceMiddleware
    // you might add other middlewares here
  )
);

export default store;
This JavaScript snippet imports the `debounceMiddleware` we created earlier along with Redux's `createStore` and `applyMiddleware` functions. It then creates a Redux store using the `rootReducer` and applies the `debounceMiddleware`. Optionally, other middlewares can be added in the `applyMiddleware` function.
// Sample Redux action creator with debounce meta property
export const sampleAction = (payload) => ({
  type: 'SAMPLE_ACTION',
  payload,
  meta: { debounce: true }
});
This JavaScript code snippet is an example of a Redux action creator that creates an action with a `meta` property indicating that the action should be debounced. The middleware will look for this property to decide whether to debounce the action.