ReactEasy
What is useRef?
useRef(initial) returns a mutable object { current: initial } that persists for the component's lifetime. Changing ref.current does not cause a re-render. It has two main uses: holding a reference to a DOM element (via the ref attribute) and storing values that must survive renders without affecting the UI, such as timer IDs or previous values.
DOM refs
const inputRef = useRef<HTMLInputElement>(null)and<input ref={inputRef} />.- After commit,
inputRef.currentis the DOM node: focus it, measure it, scroll it into view, integrate a library. - In React 19,
refis a regular prop for function components, so custom components can acceptrefwithoutforwardRef. - Callback refs (
ref={(node) => ...}) can return a cleanup function in React 19.
Instance values
- Timer and interval IDs,
AbortControllers, WebSocket instances. - Previous values, flags like "has submitted", the latest callback.
- Large mutable objects you do not want to copy.
Rules
- Do not read or write
ref.currentduring rendering (except lazy initialization:if (ref.current === null) ref.current = create()). Render output must not depend on refs, because changes are invisible to React. The React Compiler lint rulerefsflags this. - Access DOM refs in effects or event handlers, after they are attached.
- Use state, not refs, for anything shown on screen.
TypeScript
useRef<HTMLDivElement>(null) for DOM refs; useRef<number | undefined>(undefined) for mutable values.
Code example
tsx
1import { useEffect, useRef, useState } from "react";23export function Stopwatch() {4 const [elapsed, setElapsed] = useState(0);5 const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined); // instance value6 const startRef = useRef(0);7 const buttonRef = useRef<HTMLButtonElement>(null); // DOM ref89 useEffect(() => {10 buttonRef.current?.focus();11 return () => clearInterval(intervalRef.current);12 }, []);1314 function start() {15 startRef.current = Date.now() - elapsed;16 clearInterval(intervalRef.current);17 intervalRef.current = setInterval(() => setElapsed(Date.now() - startRef.current), 50);18 }1920 function stop() {21 clearInterval(intervalRef.current); // changing refs never re-renders22 }2324 return (25 <div>26 <p>{(elapsed / 1000).toFixed(2)}s</p>27 <button ref={buttonRef} onClick={start}>Start</button>28 <button onClick={stop}>Stop</button>29 </div>30 );31}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.