Languages
[Edit]
EN

React - use delayed callback with state reset

2 points
Created by:
JustMike
26150

In this short article we would like to show how to write callback function that is called only when a certain amount of time elapses.

Main assumption of the below code is to reduce number of callback function calling by canceling previous one when new one handleClick call occurs.

Quick solution:

const useDelayedCallback = (delay: number = 100) => {
  const ref = useRef();
  useEffect(() => {
    // cleaning uncalled delayer callback
    return () => {
      if (ref.current) clearTimeout(ref.current);
    };
  }, []);
  return (callback: () => void) => {
    if (ref.current) clearTimeout(ref.current);
    setTimeout(callback, delay);
  };
};

// Usage example:

const Button = () => {
  const delayCallback = useDelayedCallback();
  const handleClick = () => {
    delayCallback(() => alert('Button clicked!!!'));
  };
  return (
    <button onClick={handleClick}>Click me!!!</button>
  );
};

We will see on screen Button clicked!!! alert message when click operation will end. When we will click on button many times in short time, only one click event will effect - reduced number of clicks. 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join