Languages
[Edit]
EN

React - use delayed callback with state reset

5 points
Created by:
JustMike
27880

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 App = () => {
  const delayCallback = useDelayedCallback();
  const handleClick = () => {
    delayCallback(() => alert('Button clicked!!!'));
  };
  return (
    <button onClick={handleClick}>Click me!!!</button>
  );
};

export default App;

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
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join