JAVASCRIPT

Throttle Function Calls with Custom `useThrottle` React Hook

Optimize performance by creating a custom `useThrottle` hook in React to limit the execution rate of functions like scroll handlers or window resize listeners.

import { useState, useEffect, useRef } from 'react';

function useThrottle(value, delay) {
  const [throttledValue, setThrottledValue] = useState(value);
  const lastRan = useRef(Date.now());

  useEffect(() => {
    const handler = setTimeout(() => {
      if (Date.now() - lastRan.current >= delay) {
        setThrottledValue(value);
        lastRan.current = Date.now();
      }
    }, delay - (Date.now() - lastRan.current));

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

  return throttledValue;
}
How it works: The `useThrottle` hook takes a value and a delay, returning a throttled version of that value. It uses `setTimeout` to ensure the value updates only once within the specified `delay` period, effectively limiting the rate at which a function or state update can occur. This is particularly useful for expensive operations triggered by frequent events like scrolling or resizing, preventing excessive re-renders and improving application performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs