Languages
[Edit]
EN

React - use delayed callback (with state reset when component is unmount)

5 points
Created by:
Aston-Freeman
787

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 useDebounceCallback = (delay = 100, cleaning = true) => { // or: delayed debounce callback
    const ref = React.useRef();
    React.useEffect(() => {
      	if (cleaning) {
            // 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 = useDebounceCallback(500); // max 1 callback call per 500ms after timeout
    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!!! 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.

 

Alternative titles

  1. React - use debounce callback
  2. React - use debouncing callback
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

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.

❤️💻 🙂

Join