Prompt
Use useRef to focus a TextInput when a button is pressed. The TextInput should auto-focus when the component mounts.
Solution
Refs are React's sanctioned escape hatch from the declarative model. Focus is imperative by nature — "focus this now" is a command, not a description of UI — so it cannot be expressed as rendered output. The ref gives you a handle to the host element (the native view in React Native, the DOM node on web) to issue that command.
Mechanics: useRef(null) creates a stable { current } box that survives re-renders; passing it as ref makes React assign the host instance into .current during the commit phase. That timing is why the auto-focus lives in useEffect with [] deps — effects run after commit, so the node is guaranteed attached. Calling .focus() in the render body would fire before attachment (and would be a render-phase side effect, illegal under concurrent rendering, where the render phase can run multiple times without committing). The ?. guard covers the detached window around unmount.
The decision rule worth stating: if a value should be reflected in the UI, it's state; if it only needs to persist between renders — timer ids, previous values, element handles — it's a ref, because mutating .current triggers no render.
Red flag: Storing UI-driving values in a ref "to avoid re-renders." The screen silently stops updating — if the user should see it, it's state by definition.
Say it: "A ref is a render-persistent mutable box that doesn't trigger renders — refs are attached at commit, so imperative calls like focus belong in effects or handlers, never in the render body."