Blog>
Snippets

Throttling Actions with a Custom Middleware

Create a middleware that throttles the dispatch of certain actions to prevent overloading in Redux 5.0.0, which can be beneficial for actions triggered by user input.
function createThrottleMiddleware(timeFrame = 300) {
  let lastTime = 0;
  let timeoutId;

  return store => next => action => {
    const now = Date.now();
    if (now - lastTime < timeFrame) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        lastTime = Date.now();
        next(action);
      }, timeFrame - (now - lastTime));
    } else {
      lastTime = now;
      next(action);
    }
  };
}
This code defines a custom Redux middleware for throttling actions. It prevents an action from being dispatched if it is triggered again within a certain timeframe (default 300ms). If the action is triggered again within the timeframe, it will be dispatched only after the timeframe elapses since the last dispatch.
const { createStore, applyMiddleware } = Redux;
const throttleMiddleware = createThrottleMiddleware(1000); // throttle actions with 1 second delay
const store = createStore(reducer, applyMiddleware(throttleMiddleware));
This code sets up a Redux store with the defined throttleMiddleware. The middleware will throttle actions with a 1-second delay between dispatches.
<button id='throttleButton'>Click me</button>

<script>
  document.getElementById('throttleButton').addEventListener('click', () => {
    store.dispatch({ type: 'BUTTON_CLICKED' })
  });
</script>
This HTML and Javascript code provides a button that, when clicked, dispatches an action to the Redux store. The action 'BUTTON_CLICKED' is throttled by the middleware to prevent overloading the store with too many dispatched actions in a short time.
button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

button:active {
  background-color: #ddd;
}
This CSS styles the button with padding, font size, a pointer cursor, and a background color change on active state (i.e., when the button is being clicked).