react.useref
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
1
function TextInputWithFocusButton() {
2
const inputEl = useRef(null);
3
const onButtonClick = () => {
4
// `current` points to the mounted text input element
5
inputEl.current.focus();
6
};
7
return (
8
<>
9
<input ref={inputEl} type="text" />
10
<button onClick={onButtonClick}>Focus the input</button>
11
</>
12
);
13
}
Copied!
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
Last modified 1mo ago
Copy link