I tried to implement the debounce functionality in the react functional component. But due to some reason, it is not working.
import React from "react";
import "./styles.css";
export default function App() {
const [random, setRandom] = React.useState(Math.random());
const changeKey = () => {
setRandom(Math.random());
};
const debounce = (func, timeout = 1000) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button
onClick={() => {
debounce(changeKey(), 2000);
}}
>
<p>Click Me!</p>
</button>
{random}
</div>
);
}
here I have added the codesandbox link https://codesandbox.io/s/silent-silence-6i532c?file=/src/App.js:0-857
Consider implementing it with a hook. This one, useDebounce from react-use is very good. https://github.com/streamich/react-use/blob/master/docs/useDebounce.md