Skip to content
Advertisement

Extend the timeout after each click on react

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.

JavaScript

Advertisement

Answer

Put the timeout ID into a ref, and then you can call clearTimeout on it at the very beginning of the click handler.

JavaScript
JavaScript
Advertisement