useRef
useRef is a Hook that holds a value across renders. A ref is a small box that keeps one value while a component stays on the page.
Making a ref
The ref starts with no value.
const inputRef = useRef(null);
return <input ref={inputRef} />;Reading the value
The current property holds the stored value.
const value = inputRef.current;Focusing on click
A click can focus the input through the ref.
<button onClick={() => inputRef.current.focus()}>
Focus the input
</button>Example
import { useRef } from 'react';
export default function App() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} placeholder="Type your name" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</div>
);
}
Key points
- A ref holds one value that stays put across renders.
- Changing a ref does not make the component render again.
- A ref can point at an element on the page.
- The ref keeps its value in a property named current.
In this example, the component calls useRef at the top. The call makes a ref that starts with no value. The input takes the ref. The button focuses the input when it is clicked.
Note
A ref starts with the value passed to useRef.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does useRef return?