React
Timer example
Learn to store a timer id with useRef.
Timer example
The second typical use of useRef is to store a timer id (interval id). setInterval returns an id; you use it with clearInterval to clean up.
If you store the id in state, every update triggers another render. useRef holds it silently; you write and read without triggering a render.
Example: a seconds counter. On button click, setInterval starts and the id is written to intervalRef.current. On unmount, clearInterval(intervalRef.current) cleans up.
Cleanup with useRef
The return function of useEffect is the cleanup. Right before the component unmounts, React calls this function. return () => clearInterval(intervalRef.current); safely stops the timer.
If you don't clean up, the timer keeps running in the background even after the component is gone and tries to update state. That means bugs and memory leaks.
So every component using setInterval must return a cleanup function. The useRef + useEffect pair enforces this discipline.
Exercise Seconds counter
Complete the skeleton. Write a Timer component. Create intervalRef = useRef(null). Inside useEffect, use setInterval to increment setSeconds every second; write the id to intervalRef.current. Return clearInterval(intervalRef.current) as cleanup. Show <p>{ '{ seconds }' }</p>. Keep seconds as state. Export it.
Show example solution
import { useRef, useEffect, useState } from "react";
function Timer() {
const intervalRef = useRef(null);
const [seconds, setSeconds] = useState(0);
useEffect(() => {
intervalRef.current = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(intervalRef.current);
}, []);
return <p>{seconds}</p>;
}
export default Timer;
Test yourself
-
Why store timer id in ref not state?
- To avoid triggering renders
- It's faster
- State can't be used
- Cleanup isn't needed
Show answer
To avoid triggering renders — useRef stores the id without triggering renders.
-
Cleanup function
To clean up the timer, call ____.
Show answer
To clean up the timer, call clearInterval.
-
Match the timer steps
- setInterval
- Starts
- intervalRef
- Holds id
- clearInterval
- Cleans
- useEffect
- Side effect
Next lesson: Summary - useRef