0
0
ReactHow-ToBeginner · 3 min read

How to Create a Timer in React: Simple Guide with Examples

To create a timer in React, use the useState hook to track time and useEffect to set up an interval that updates the timer. Clear the interval inside useEffect cleanup to avoid memory leaks.
📐

Syntax

Use useState to hold the timer value and useEffect to start and clear the timer interval.

  • useState(initialValue): stores the current timer count.
  • useEffect(() => { ... }, []): runs code on component mount and cleanup on unmount.
  • setInterval(callback, delay): calls callback repeatedly every delay milliseconds.
  • clearInterval(id): stops the interval to prevent memory leaks.
jsx
import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return <div>Timer: {count} seconds</div>;
}
Output
Timer: 0 seconds (then increments every second)
💻

Example

This example shows a simple timer that counts seconds from zero, updating every second. It uses React hooks to manage state and side effects safely.

jsx
import React, { useState, useEffect } from 'react';

export default function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return <div>Timer: {seconds} seconds</div>;
}
Output
Timer: 0 seconds (increments every second)
⚠️

Common Pitfalls

Common mistakes when creating timers in React include:

  • Not clearing the interval with clearInterval, causing memory leaks.
  • Updating state incorrectly inside setInterval, leading to stale values.
  • Missing the empty dependency array [] in useEffect, causing multiple intervals.
jsx
import React, { useState, useEffect } from 'react';

// Wrong: Missing cleanup and stale state
function WrongTimer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count + 1); // uses stale count
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

  return <div>{count}</div>;
}

// Right: Cleanup and functional update
function RightTimer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(prev => prev + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <div>{count}</div>;
}
📊

Quick Reference

Tips for creating timers in React:

  • Always clear intervals in useEffect cleanup.
  • Use functional updates setCount(prev => prev + 1) to avoid stale state.
  • Use an empty dependency array [] to run timer setup only once.
  • Consider using useRef if you need to store interval IDs.

Key Takeaways

Use useState to hold timer value and useEffect to manage interval lifecycle.
Always clear intervals in useEffect cleanup to prevent memory leaks.
Use functional state updates inside setInterval to avoid stale values.
Include an empty dependency array in useEffect to run timer setup once.