useRef
Reach into the DOM directly, or remember a value across renders without re-rendering.
What you will learn
- Reference a DOM element with useRef
- Focus an input programmatically
- Know when to use ref vs state
A direct handle to an element
useRef gives you a reference to a real DOM element so you can do things like focus an input or measure it.
function App() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} placeholder="Click the button to focus me" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</div>
);
}Step by step: useRef(null) creates an empty box called inputRef. We attach it to the input with ref={inputRef}, so React fills inputRef.current with the real input element. When the button is clicked, inputRef.current.focus() reaches into that real element and focuses it — the cursor jumps into the box. This is how you do direct DOM actions (focus, scroll, measure) that state cannot do.
Note: Output: An input and a Focus the input button. Click the button and the text box gains focus (the cursor appears inside it), ready for typing.
Note: Unlike state, changing a ref does not trigger a re-render. Use state for data shown in the UI; use ref for direct DOM access or values you want to remember without re-rendering.
Q. A key difference between useRef and useState is:
✍️ Practice
- Use
useRefto focus an input when a button is clicked. - Use
useRefto read the current value of an uncontrolled input.
🏠 Homework
- Build a search box that auto-focuses when the page loads (ref + useEffect).