Manipulate DOM Elements with useRef in React

InstructorRyan Harris

Share this video with your friends

Send Tweet

The useRef hook allows us to leverage React refs within our function components. Refs can be assigned to DOM elements in order to allow us to manipulate them directly.

It is important, however, to note that this is somewhat of an anti-pattern in React as JavaScript frameworks usually handle updating the browser DOM after the virtual DOM has changed.

useRef only takes one argument: its initial value. In the code snippet below, you can see how it is then assigned to an <input />:

// Instantiate the ref
const inputRef = useRef(null);

// Assign `inputRef` to the <input /> element
<input ref={inputRef} type="search" />