Custom useInterval Hook
ReactJS
Hard
5 views
Problem Description
Create a useInterval hook and use it to increment a number.
Output Format
Render a React component.
Constraints
Store callback in ref and run interval from effect.
Official Solution
import React, { useEffect, useRef, useState } from 'react';
function useInterval(callback, delay) {
const cbRef = useRef(callback);
useEffect(() => {
cbRef.current = callback;
}, [callback]);
useEffect(() => {
if (delay == null) return;
const id = setInterval(() => cbRef.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
export default function App() {
const [n, setN] = useState(0);
const [running, setRunning] = useState(true);
useInterval(() => setN((x) => x + 1), running ? 500 : null);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode interval</h2>
<div style={{ fontSize: 28, fontWeight: 800 }}>{n}</div>
<button type='button' onClick={() => setRunning((v) => !v)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>{running ? 'Pause' : 'Resume'}</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!