EN
React - use delayed callback (with state reset when component is unmount)
5
points
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.