Listing 11-5: Creating a new timer with each render
Check the console to see the timer.
import {useEffect,useState} from 'react';
function TimerRestartFun(props){
const [count,setCount] = useState(0);
useEffect(() => {
let time = 0;
const interval = setInterval(() => {
console.log(time++);
}, 1000);
return () => clearInterval(interval);
});
return (<p>Check the console to see the timer.
<button onClick={()=>setCount((prev)=>prev+1)}>{count}</button>
</p>
);
}
export default TimerRestartFun;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.