useRef

useRef is like a box that can hold a mutable value in its .current property.

Refs are used primarily as a way to access the DOM.

If you pass a ref object to React with ref={myRef}, React will set its .current property to the corresponding DOM node whenever that node changes.

useRef() creates a plain JavaScript object.

The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

useRef doesn't notify you when its content changes, and doesn't trigger a re-render.

In this example, we're initially setting the input element variable (inputEl) to benull.

const inputEl = useRef(null);

The hook then looks through the DOM for ref={inputEl}, and updates that variable to reference that element.

<input ref={inputEl} type="text" />

Then we use the button to do something with that element (in this case, focus on it).

const onButtonClick = () => {inputEl.current.focus();};

<button onClick={onButtonClick}>Focus on the input</button>

Example