Listing 11-6: Passing an empty array to only run useEffect on mount
Check the console to see the timer.
import {useEffect,useState} from 'react';
function TimerOnceFun(props){
const [count,setCount] = useState(0);
useEffect(() => {
let time = 0;
const interval = setInterval(() => {
console.log(time++);
if(time===10){
console.log(`time's up!`);
clearInterval(interval);
}
}, 1000);
return () => clearInterval(interval);
},[]);
return (<p>Check the console to see the timer.
<button onClick={()=>setCount((prev)=>prev+1)}>{count}</button>
</p>
);
}
export default TimerOnceFun;
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.