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.

You will learn
  • How useRef works, 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
What's an "escape hatch"? Most of the time React handles everything for you. Escape hatches are tools for stepping outside React: talking to the browser directly, or to other systems. Use them only when you need to, because most code shouldn't need them.

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

RefState
Create withuseRef(initial) β†’ { current }useState(initial) β†’ [value, setValue]
Changing it re-renders?NoYes
Mutable?Yes: ref.current = xNo: use the setter
Read during rendering?Avoid itYes, that's what it's for
Use forTimer IDs, DOM elements, values that don't affect the screenAnything shown on the screen
Rule of thumb If it's shown on screen, use state. If it's just remembered behind the scenes, use a ref.
Don't read or write 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

  1. Create the ref: useRef(null).
  2. Attach it: <input ref={inputRef} />. React puts the DOM element into inputRef.current after the commit.
  3. 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:

Older code Before React 19 this needed forwardRef(...). You'll still see it in older tutorials.
Don't change the parts of the DOM React manages Focusing, scrolling and measuring are safe. Adding or removing elements that React rendered (for example 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 in myRef.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