ReactJS Program to Effect Cleanup With Timer with Explanation
ReactJS
Medium
Hooks & Effects
24 views
1 min read
87 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around cleanup, timer, react. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Start a timer in useEffect and clean it up on unmount.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use setInterval and return a cleanup function.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useEffect, useState } from 'react';
export default function App() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id);
}, []);
return (
<div style={{ padding: 16 }}>
<strong>meetcode timer</strong>
<div style={{ marginTop: 8, fontSize: 24, fontWeight: 800 }}>{seconds}s</div>
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Start a timer in useEffect and clean it up on unmount.
Input / Output
Output
Render a React component.
Constraints
Use setInterval and return a cleanup function.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Difficulty
Medium
ReactJS
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id);
}, []);
return (
<div style={{ padding: 16 }}>
<strong>meetcode timer</strong>
<div style={{ marginTop: 8, fontSize: 24, fontWeight: 800 }}>{seconds}s</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!