useInterval Hook
ReactJS
Hard
7 views
Problem Description
Create a useInterval hook and use it to build a timer.
Output Format
Render a React component.
Constraints
Keep the latest callback in a ref and manage interval in an effect.
Official Solution
import React, { useEffect, useRef, useState } from 'react';
function useInterval(callback, delay) {
const saved = useRef(callback);
useEffect(() => {
saved.current = callback;
}, [callback]);
useEffect(() => {
if (delay == null) return;
const id = setInterval(() => saved.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
export default function App() {
const [running, setRunning] = useState(false);
const [seconds, setSeconds] = useState(0);
useInterval(() => {
setSeconds((s) => s + 1);
}, running ? 1000 : null);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode timer</h2>
<div style={{ fontSize: 28, fontWeight: 800 }}>{seconds}s</div>
<div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
<button type='button' onClick={() => setRunning((v) => !v)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>{running ? 'Pause' : 'Start'}</button>
<button type='button' onClick={() => setSeconds(0)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reset</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!