Effect Cleanup With Timer
ReactJS
Medium
6 views
Problem Description
Start a timer in useEffect and clean it up on unmount.
Output Format
Render a React component.
Constraints
Use setInterval and return a cleanup function.
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!
No comments yet. Start the discussion!