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.current is the DOM node: focus it, measure it, scroll it into view, integrate a library.
  • In React 19, ref is a regular prop for function components, so custom components can accept ref without forwardRef.
  • 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.current during 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 rule refs flags 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";
2
3export function Stopwatch() {
4 const [elapsed, setElapsed] = useState(0);
5 const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined); // instance value
6 const startRef = useRef(0);
7 const buttonRef = useRef<HTMLButtonElement>(null); // DOM ref
8
9 useEffect(() => {
10 buttonRef.current?.focus();
11 return () => clearInterval(intervalRef.current);
12 }, []);
13
14 function start() {
15 startRef.current = Date.now() - elapsed;
16 clearInterval(intervalRef.current);
17 intervalRef.current = setInterval(() => setElapsed(Date.now() - startRef.current), 50);
18 }
19
20 function stop() {
21 clearInterval(intervalRef.current); // changing refs never re-renders
22 }
23
24 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.

Open in study app