Sub topic 5
Focusing, scrolling, and measuring
This chapter covers the imperative DOM actions you reach for most often with useRef: focusing an element, scrolling it into view, and measuring its size and position. It assumes you know useState, basic useEffect, and how to attach a ref to a DOM element with the ref attribute.
Why these actions need a ref
React is declarative. You describe what the screen should look like for a given state, and React updates the DOM to match. Some browser actions have no declarative equivalent. There is no focused prop on an <input> that you can set to move keyboard focus there on demand. The same is true of "scroll this into view" and "how tall is this box right now?"
For these cases you ask React for the DOM node and call the browser's own methods on it. A ref is the tool for that. React sets ref.current to the node after it mounts, and you call methods such as focus(), scrollIntoView(), and getBoundingClientRect() on it.
Focusing an element
The smallest example is a button that focuses an input.
import { useRef } from 'react';
export function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}The ref starts as null. After React mounts the <input>, it sets inputRef.current to the DOM node. The click handler runs later, so the node exists by then and focus() works.
Focus on mount
To focus an element when the component first appears, do it in an effect. Effects run after the DOM is committed, so the ref is already filled in.
import { useEffect, useRef } from 'react';
export function NameField() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} placeholder="Your name" />;
}For this specific case, the autoFocus attribute is often simpler. Use a ref when focus depends on a condition or an event, for example moving focus to an error field after a failed submit.
Focus and accessibility
Moving focus is a significant change for keyboard and screen reader users. Follow a few rules:
- Move focus only in response to a user action or a clear change of context, such as opening a dialog.
- Avoid stealing focus on page load unless the page has one obvious purpose, such as a search page.
- After closing a dialog, return focus to the control that opened it.
Scrolling an element into view
scrollIntoView() scrolls the nearest scrollable ancestors so the element becomes visible.
import { useRef } from 'react';
export function Section() {
const endRef = useRef(null);
return (
<>
<button onClick={() => endRef.current.scrollIntoView({ behavior: 'smooth' })}>
Jump to the end
</button>
<div style={{ height: 2000 }}>Long content</div>
<p ref={endRef}>The end</p>
</>
);
}The options object controls the motion and alignment:
| Option | Common values | Effect |
|---|---|---|
| `behavior` | `'auto'`, `'smooth'` | Jump instantly or animate |
| `block` | `'start'`, `'center'`, `'end'`, `'nearest'` | Vertical alignment |
| `inline` | `'start'`, `'center'`, `'end'`, `'nearest'` | Horizontal alignment |
Use block: 'nearest' when you want the least movement. If the element is already visible, nothing scrolls. Smooth scrolling is a request, not a guarantee. Users who set "reduce motion" in their operating system may expect no animation, so consider checking window.matchMedia('(prefers-reduced-motion: reduce)') before choosing 'smooth'.
Scrolling after a state update
A common bug is scrolling to an element that React has not rendered yet. Suppose you append a message to a chat list and then scroll to the last item:
import { useRef, useState } from 'react';
export function Chat() {
const [messages, setMessages] = useState(['Hello']);
const lastRef = useRef(null);
function send() {
setMessages([...messages, `Message ${messages.length + 1}`]);
// Bug: the new item is not in the DOM yet, so this scrolls to the old last item.
lastRef.current?.scrollIntoView({ behavior: 'smooth' });
}
return (
<>
<ul style={{ height: 120, overflow: 'auto' }}>
{messages.map((text, i) => (
<li key={i} ref={i === messages.length - 1 ? lastRef : null}>
{text}
</li>
))}
</ul>
<button onClick={send}>Send</button>
</>
);
}State updates are queued, and the DOM does not change until React re-renders. The fix is to scroll in an effect that runs after the new message is committed:
import { useEffect, useRef, useState } from 'react';
export function Chat() {
const [messages, setMessages] = useState(['Hello']);
const lastRef = useRef(null);
useEffect(() => {
lastRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
return (
<>
<ul style={{ height: 120, overflow: 'auto' }}>
{messages.map((text, i) => (
<li key={i} ref={i === messages.length - 1 ? lastRef : null}>
{text}
</li>
))}
</ul>
<button onClick={() => setMessages([...messages, `Message ${messages.length + 1}`])}>
Send
</button>
</>
);
}React also offers flushSync from react-dom, which forces a synchronous update so you can read the DOM right after it. It is a last resort. The effect approach is simpler and does not block rendering.
Measuring an element
getBoundingClientRect() returns an element's size and its position relative to the viewport. The returned object includes width, height, top, left, right, and bottom.
import { useRef, useState } from 'react';
export function MeasureBox() {
const boxRef = useRef(null);
const [size, setSize] = useState(null);
function measure() {
const rect = boxRef.current.getBoundingClientRect();
setSize({ width: Math.round(rect.width), height: Math.round(rect.height) });
}
return (
<>
<div ref={boxRef} style={{ width: '50%', padding: 16, background: '#eef' }}>
Resize the window, then measure me.
</div>
<button onClick={measure}>Measure</button>
{size && <p>{size.width} x {size.height}</p>}
</>
);
}The measurement is stored in state, not in a ref, because it is displayed. That follows the rule from earlier chapters: if the value appears on screen, React must know about it so it can re-render.
Reading versus writing
Reading layout values such as getBoundingClientRect() or offsetHeight forces the browser to compute layout. Doing this in an event handler is fine. Doing it in a loop that also writes styles can cause repeated forced layouts and slow the page. Batch your reads first, then do your writes.
Measuring before paint
If you must measure and then adjust the layout before the user sees anything, such as positioning a tooltip next to its anchor, use useLayoutEffect instead of useEffect. It runs after the DOM updates but before the browser paints, which prevents a visible flicker. Use it only for this purpose, because it blocks painting.
Tracking size changes
A single measurement goes stale when the window or content resizes. For continuous tracking, combine a ref with ResizeObserver inside an effect and clean it up:
import { useEffect, useRef, useState } from 'react';
export function LiveWidth() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const node = boxRef.current;
const observer = new ResizeObserver(([entry]) => {
setWidth(Math.round(entry.contentRect.width));
});
observer.observe(node);
return () => observer.disconnect();
}, []);
return (
<div ref={boxRef} style={{ resize: 'horizontal', overflow: 'auto', border: '1px solid' }}>
Width: {width}px
</div>
);
}The effect copies boxRef.current into a local variable node and cleans up with disconnect(). This avoids surprises if the ref changes before cleanup runs.
Edge cases and common mistakes
- The ref is
null. Before mount, or when the element is conditionally not rendered,ref.currentisnull. Calling.focus()on it throws aTypeError. Use optional chaining (ref.current?.focus()) when the element may be absent. - Focusing a hidden element.
focus()does nothing on an element withdisplay: noneor on one that is not focusable. A<div>needstabIndex={-1}ortabIndex={0}before it can receive focus. - Reading refs during render. Calling
ref.current.getBoundingClientRect()in the component body is wrong. On the first render, the node does not exist, and render must stay pure. Measure in handlers or effects. - Refs on custom components. Putting
refon your own component does not give you a DOM node unless that component forwards the ref. A later chapter covers this. - Scrolling the wrong container.
scrollIntoViewscrolls every scrollable ancestor, which can move the whole page unexpectedly. To scroll only one container, set itsscrollTopdirectly through its own ref.
Exercise
A chat component calls setMessages(...) and then immediately calls lastRef.current.scrollIntoView() in the same click handler. The list scrolls to the previous last message instead of the new one. Why does this happen, and how do you fix it?
Show answer
The state update is queued, so the new message is not in the DOM when scrollIntoView runs, and lastRef still points to the old last item. Fix it by moving the scroll into a useEffect that depends on messages. Effects run after React commits the new DOM, so lastRef.current points to the new item.
Exercise
You want to show an element's width on screen and keep it correct as the user resizes the window. Should the width live in a ref or in state, and which browser API and React hook do you use to keep it current?
Show answer
Store the width in state, because it is displayed and React must re-render when it changes. Use a ref to hold the element, and create a ResizeObserver inside a useEffect that calls setWidth. Disconnect the observer in the effect's cleanup function.