Suppose there’s the following simple component. When I click on the button, the message will change to Clicked
for 1 second and then goes back to -
. However, when I spam the button, I want the title to be Clicked
but it should go back to -
after the last click of the button. Basically, I want each click to expand the timeout.
If this was a simple JS function, I would just clear the interval after each click and set another timeout. However, I’m not sure how to achieve the same result using react hooks.
import ReactDOM from 'react-dom';
import {useEffect, useState} from 'react';
import './index.css';
const Test = () => {
const [message, setMessage] = useState("-");
const buttonClick = () => {
setMessage("Clicked");
}
useEffect(() => {
if(message !== "-") {
const id = setTimeout(() => {
console.log("Running Interval");
setMessage("-");
}, 1000);
return () => {
console.log("Clearing Interval");
clearTimeout(id);
}
}
}, [message]);
return (
<article>
<header>
{message}
</header>
<button onClick={buttonClick}>button</button>
</article>
);
}