What is a ref in React and what is it used for?
Short answer
A ref gives you a way to directly access an actual DOM element or to store a value that does not need to cause a re render when it changes.
Advertisement
AModel answer
A ref gives you a way to directly access an actual DOM element or to store a value that does not need to cause a re render when it changes. Common uses include focusing an input field, measuring an element's size, or keeping track of a value between renders without triggering an update.
function TextInput() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus the input</button>
</>
);
}Real-world example
A search page automatically focuses its search input the moment a user clicks a search icon, using a ref to directly call the focus method on the actual input element.
Likely follow-ups
- Why does changing a ref's value not cause a component to re render?
- Can you use a ref to store something other than a DOM element?
Related topics