useRef is a React hook that lets you store values that:
const myRef = useRef(initialValue);
Returns an object: { current: initialValue }
Store values that need to persist but shouldn't cause re-renders.
Example: Stopwatch
function Stopwatch() {
const [time, setTime] = useState(0);
const intervalRef = useRef(null);
const start = () => {
if (intervalRef.current) clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
setTime(prev => prev + 1);
}, 1000);
};
const stop = () => {
clearInterval(intervalRef.current);
intervalRef.current = null;
};
const reset = () => {
clearInterval(intervalRef.current);
intervalRef.current = null;
setTime(0);
};
return (
<div>
<p>Time: {time}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
<button onClick={reset}>Reset</button>
</div>
);
}
Get direct reference to DOM elements to call their methods.
Example: Auto-focus Input
function SearchBox() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" placeholder="Search..." />
<button onClick={focusInput}>Focus</button>
</div>
);
}
Example: Video Player
function VideoPlayer({ src }) {
const videoRef = useRef(null);
return (
<div>
<video ref={videoRef} src={src} width="600" />
<button onClick={() => videoRef.current.play()}>Play</button>
<button onClick={() => videoRef.current.pause()}>Pause</button>
<button onClick={() => videoRef.current.currentTime = 0}>Restart</button>
</div>
);
}
Example: Form Handling