CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.jsx
import { useRef, useEffect, useState } from "react";

// Write the Timer component here

Sample solution

App.jsx
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why store timer id in ref not state?

  • To avoid triggering renders Correct answer
  • It's faster
  • State can't be used
  • Cleanup isn't needed

Explanation: useRef stores the id without triggering renders.

2 Cleanup function

Question
To clean up the timer, call ____.
Answer
To clean up the timer, call clearInterval.

Explanation: clearInterval cleans up the interval.

3 Match the timer steps

Term Meaning
setInterval Starts
intervalRef Holds id
clearInterval Cleans
useEffect Side effect

All lessons in Beginner