Enhancing Performance in React with Debounce and Throttle Custom HooksFeb 2024
featured image

In the world of React development, optimizing performance is key to delivering a smooth user experience. Two powerful techniques for managing function calls, especially in scenarios like handling user input or API requests, are debounce and throttle.

Debounce

ensures that a function is not called repeatedly in a short span of time, but rather only after a certain delay has passed since the last invocation. This is particularly useful for scenarios like handling search inputs, where you want to wait for the user to finish typing before triggering a search.

import { useEffect, useState } from 'react';

export function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

Throttle

on the other hand, limits the rate at which a function can be called. It ensures that the function is executed at most once per specified interval. This is handy for scenarios such as handling scroll events or preventing excessive API requests.

import { useCallback, useRef } from 'react';

export function useThrottle(callback, delay) {
  const timeoutRef = useRef(null);

  const throttledCallback = useCallback(
    (...args) => {
      if (!timeoutRef.current) {
        callback(...args);
        timeoutRef.current = setTimeout(() => {
          timeoutRef.current = null;
        }, delay);
      }
    },
    [callback, delay],
  );

  return throttledCallback;
}

By incorporating these custom hooks into your React components, you can effectively manage the timing of function calls, ensuring optimal performance and a more responsive user interface. Whether it's debouncing user inputs or throttling API requests, these techniques can significantly enhance your application's efficiency.