Simple React Counter that automatically increases the count every second.
✅ Counter Component (Auto Increment)
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(timer); // cleanup
}, []);
return <h2>Count: {count}</h2>;
}
export default Counter;
🧠 How It Works
useStatestores the countuseEffectruns once on mount ([])setIntervalincrements every 1 second- Cleanup prevents memory leaks on unmount
🎯 Short Interview Answer
Use
useEffectwithsetIntervalto update state every second and clear the interval on unmount.
⭐ One-line summary
useEffect + setInterval creates an auto-incrementing counter safely.