const [yValue, setYValue] = useState(6); useEffect(() => { // The interval ID returned by setInterval is // stored in the interval variable. const interval = setInterval(() => { setYValue((prevYValue) => prevYValue + 1); }, 1000); // The effect function returns a cleanup function. // This cleanup function is called when the component unmounts or // when the effect is re-run. // // In this case, it clears the interval using clearInterval to // prevent memory leaks and stop the timer. return () => clearInterval(interval); }, []);
The useEffect hook takes two arguments:
a function
a dependency array.
In this case, the dependency array [] is empty, indicating that the effect should only run once when the component mounts.