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> ); }
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.
const Test = () => { const [message, setMessage] = React.useState("-"); const timeoutIdRef = React.useRef(); const handleClick = () => { setMessage("Clicked"); clearTimeout(timeoutIdRef.current); timeoutIdRef.current = setTimeout(() => { setMessage("-"); }, 1000); }; // cleanup, if desired // React.useEffect(() => clearTimeout(timeoutIdRef.current), []); return ( <article> <header> {message} </header> <button onClick={handleClick}>button</button> </article> ); } ReactDOM.render(<Test />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>