React - use delayed callback with state reset

5 points
Created by:

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:

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

const useDelayedCallback = (delay = 100) => {
    const ref = React.useRef();
    React.useEffect(() => {
        // cleaning uncalled delayed callback with component destroying
        return () => {
          	if (ref.current) clearTimeout(ref.current);
    }, []);
    return (callback) => {
        if (ref.current) clearTimeout(ref.current);
        ref.current = setTimeout(callback, delay);

// Usage example:

const App = () => {
    const delayCallback = useDelayedCallback(500); // max 1 callback per 500ms
    const handleClick = () => {
      	delayCallback(() => console.log('Button clicked!!!'));
    return (
      <button onClick={handleClick}>Click me many times!!!</button>

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

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. 


React - use delayed callback with state reset
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.

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