Effects: The Ghost Timer
Mission
Manage the lifecycle of side effects and write cleanup functions so your app never leaks memory.
Tasks
- 1
Create a state for the seconds, starting at
0. - 2
Write a
useEffectthat starts asetIntervalticking every 1000ms. - 3
Inside the interval, log
'Tick...'so you can watch it in the console. - 4
Update the seconds with the functional form of the setter.
- 5
Return a cleanup function that stops the interval when the component unmounts.
import React, { useState, useEffect } from 'react'; // THIS IS THE COMPONENT YOU HAVE TO FIX function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { // Tip: const id = setInterval(...) // 1. Create your interval here // 2. RETURN a cleanup function: () => clearInterval(id) }, []); return ( <div style={{ border: '2px solid #646cff', padding: '20px', borderRadius: '8px', margin: '20px 0' }}> <h2>Time: {seconds}s</h2> <p style={{ fontSize: '0.8rem', color: '#888' }}>Open the console to see the logs</p> </div> ); } export default function App() { const [show, setShow] = useState(true); return ( <div style={{ padding: '20px', fontFamily: 'sans-serif', textAlign: 'center' }}> <h1>The Ghost Timer</h1> <button onClick={() => setShow(!show)} style={{ background: show ? '#ff4444' : '#44ff44', color: 'white', border: 'none', padding: '10px 20px', borderRadius: '5px', cursor: 'pointer' }} > {show ? "Hide timer" : "Show timer"} </button> {show && <Timer />} {!show && <p style={{ marginTop: '20px' }}>Component unmounted. Is the log still running in the console?</p>} </div> ); }
Requirements
0/6Starts a setInterval inside useEffect (not run yet)
Keeps the interval id in a variable (not run yet)
Updates the seconds with setSeconds(s => s + 1) (not run yet)
The effect returns a cleanup function that calls clearInterval (not run yet)
Does not run `return clearInterval(id)` immediately (not run yet)
Uses an empty dependency array so the interval is created once (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.