React
Beginner
1 min read
useRef for DOM Access and Persisting Values
Example
import { useRef, useEffect, useState } from 'react';
function AutoFocusInput() {
const inputRef = useRef(null);
// Focus the input after mount
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} placeholder="I get focus on mount" />;
}
function StopwatchWithRef() {
const [elapsed, setElapsed] = useState(0);
const intervalRef = useRef(null); // stores timer ID – NOT state
function start() {
if (intervalRef.current !== null) return; // already running
const startTime = Date.now() - elapsed;
intervalRef.current = setInterval(() => {
setElapsed(Date.now() - startTime);
}, 10);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
return (
<div>
<p>{(elapsed / 1000).toFixed(2)}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}