Chapter 12 Β· Escape Hatches
Refs
A ref is a "secret pocket" where a component keeps a value that doesn't affect what's on screen. Refs are also how you reach real DOM elements.
- How
useRefworks, and how it differs from state - When to use a ref, for example to store a timer ID
- How to access DOM elements (focus, scroll)
- How to pass a ref to your own component
Adding a ref
useRef(0) returns an object like { current: 0 }. You can read and change ref.current freely. React keeps the same object between renders, but changing it does not cause a re-render.
Example: a stopwatch
A stopwatch needs both: the times are shown on screen (so they're state), but the interval ID is only needed to stop the timer (so it's a ref).
Refs vs state
| Ref | State | |
|---|---|---|
| Create with | useRef(initial) β { current } | useState(initial) β [value, setValue] |
| Changing it re-renders? | No | Yes |
| Mutable? | Yes: ref.current = x | No: use the setter |
| Read during rendering? | Avoid it | Yes, that's what it's for |
| Use for | Timer IDs, DOM elements, values that don't affect the screen | Anything shown on the screen |
ref.current during rendering
Use refs in event handlers and effects. Reading a ref while rendering makes your component unpredictable, because React doesn't know when it changes. The one exception is lazily setting it once: if (!ref.current) ref.current = new Thing().
Manipulating the DOM with refs
React updates the DOM for you, but sometimes you need the real element: to focus an input, scroll to something, or measure its size.
Focusing an input
- Create the ref:
useRef(null). - Attach it:
<input ref={inputRef} />. React puts the DOM element intoinputRef.currentafter the commit. - Use it in an event handler:
inputRef.current.focus().
Scrolling to an element
A ref to your own component
In React 19, ref is a normal prop for your own components. Pass it through to a DOM element:
forwardRef(...). You'll still see it in older tutorials.ref.current.remove()) confuses React and can crash your app. To change what's shown, change state.
More examples
Example 1: play and pause a video
Example 2: scroll a chat to the newest message
flushSync forces React to update the DOM synchronously, so the scroll happens after the new message is on the page. (The index key is fine here, because messages are only ever added at the end.)
Example 3: measuring an element
Example 4: remembering a value without re-rendering
Recap
useRef(initial)gives a{ current }box that survives re-renders and doesn't trigger them.- Use refs for timer IDs, DOM elements and other "behind the scenes" values. Use state for what's shown on screen.
<input ref={myRef} />gives you the real element inmyRef.current.- Use refs in event handlers and effects, not during rendering.
Exercises
1. Auto-focus on button click
Make a search box with a "π Search" button. Clicking the button focuses the input.
Show solution
2. Why doesn't it update?
Show answer
Changing a ref doesn't re-render, so the text never updates. Because the count is shown on screen, it should be state: const [count, setCount] = useState(0).
3. Ref or state? π’ easy
For each item, choose ref or state: (a) the text in a search box, (b) a setTimeout ID, (c) whether a modal is open, (d) a DOM <canvas> element, (e) the number of times an API was called, used only for logging.
Show answer
(a) state (shown) Β· (b) ref Β· (c) state (affects the UI) Β· (d) ref Β· (e) ref (not shown).
4. Select all π’ easy
Make an input showing a share link, with a "Copy link" button that selects all the text in the input (inputRef.current.select()).
Show solution
5. Back to top π’ easy
Put a heading at the top of a long page (render 50 paragraphs), with a "Back to top" button at the bottom that smoothly scrolls to the heading.
Show solution
6. Focus the first empty field π‘ medium
Make a form with name and email inputs. On submit, if a field is empty, prevent submission and focus the first empty field.
Show solution
7. Your own input component with a ref π‘ medium
Create FancyInput (with a label and border styling) that accepts a ref prop, so the parent can focus it.
Show solution
8. Stopwatch with laps π‘ medium
Extend the stopwatch with a "Lap" button that records the current time in a laps array (state) and lists the laps below it. Add a "Reset" button too.
Show solution
9. Double-click guard π‘ medium
A "Pay" button must not fire twice if it's clicked quickly. Use a ref as a lock: ignore clicks that come within 2 seconds of the last accepted one.
Show solution
A ref works well here: the lock doesn't need to show on screen, and it updates instantly (state would only update on the next render).
10. Debounced search π΄ hard
As the user types, show "Searching for: X" only after they've stopped typing for 500ms. Store the timeout ID in a ref, and clear it on every keystroke.
Show solution
π Official docs: Referencing Values with Refs Β· Manipulating the DOM with Refs