React useEffect Hook Challenge 2025

🎯 React useEffect Hook Challenge (2025)

Learn how to create a timer using useEffect and dependencies in React. This is a common beginner-to-intermediate level challenge.

🧠 Requirements:

  • Display a timer starting from 0
  • Add Start and Stop buttons
  • Use useEffect with a dependency array

💻 React Code:

 import React, { useState, useEffect } from 'react'; const TimerChallenge = () => { const [count, setCount] = useState(0); const [isRunning, setIsRunning] = useState(false); useEffect(() => { let interval; if (isRunning) { interval = setInterval(() => { setCount(prev => prev + 1); }, 1000); } return () => clearInterval(interval); }, [isRunning]); return ( 

⏱ Timer: {count} sec

); }; export default TimerChallenge;

📘 Explanation:

  • useEffect runs only when isRunning changes
  • If isRunning is true, a new interval starts
  • When isRunning becomes false or component unmounts, interval is cleared

🔥 Bonus Challenges:

  • Add a "Reset" button
  • Save timer value in localStorage
  • Disable "Start" while running and "Stop" while paused