React Foundations · Effects & Refs

useRef for DOM access

useRef for DOM access

React usually updates the DOM for you. But some jobs need the actual element: focusing an input, scrolling a list into view, starting a video. For those, keep the node in a ref.

Pass the ref to an element's ref prop, and React fills in ref.current once the element is on the page:

const inputRef = useRef(null);

<input ref={inputRef} />;

current starts as null. It is only filled after React has rendered the element, so read it inside an effect or an event handler, never during render. From there you can call any DOM method — focus(), scrollIntoView(), play().

useEffect(() => {
  inputRef.current?.focus();
}, []);

This is an escape hatch. React manages the DOM for you in almost every case, so reach for a ref only when you truly need to talk to the node yourself.

In React 19 a ref is also a regular prop, so a component can accept ref and pass it straight to a DOM node without forwardRef.

Your job is to focus an input in App.jsx when the component mounts.

Challenge

A search box is on screen, but the cursor is not in it yet. Export an App component from App.jsx that renders a text input and focuses it on mount, using a ref attached to the input.

The Test renders your component and expects the input to be the active element. The starter renders an input but never focuses it, so the Test fails.

App.jsx
export function App() {
  return <input />;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.