A clock starts a timer in an effect and stops it in the cleanup. Watch it tick, then hide the clock.
React · beginner · 8 min · 35 steps · free
import { useState, useEffect } from 'react';
function Clock() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
console.log('timer started');
return () => {
clearInterval(id);
console.log('timer stopped');
};
}, []);
return <p>{seconds} s</p>;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<div>
{show && <Clock />}
<button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} clock</button>
</div>
);
}<App> for the first time: it calls the App function.useState runs for the first time, so React stores the starting value for show and returns it: true.App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.<Clock> for the first time: it calls the Clock function.useState runs for the first time, so React stores the starting value for seconds and returns it: 0.useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.Clock returns JSX: a description of what the screen should show, <p>0 s</p>. React has not changed the page yet.setInterval starts a timer that ticks every second; id is its number.setSeconds with an update function. React works this one out at once: s = 0 → 1.<Clock> again (render 2): it calls Clock once more, from the top.useState returns the value React has kept for seconds: 1. The starting value is only used on the first render.useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.Clock returns JSX: a description of what the screen should show, <p>1 s</p>. React has not changed the page yet.<Clock> again (render 3): it calls Clock once more, from the top.s = 1. It returns 2, the new value.useState returns the value React has kept for seconds: 2. The starting value is only used on the first render.useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.Clock returns JSX: a description of what the screen should show, <p>2 s</p>. React has not changed the page yet.setShow(!show) does not change show right away: React queues the update and will render again. In this call show is still true.<App> again (render 2): it calls App once more, from the top.useState returns the value React has kept for show: false. The starting value is only used on the first render.App returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.clearInterval(id) stops the timer. Nothing will tick any more.Answer: When the component is removed
Answer: The timer keeps running after Clock is gone
← Effect Dependencies · Loading Data in an Effect →