Understanding the useRef Hook Design
Learn how React creates a ref for direct DOM interaction.
We'll cover the following...
We'll cover the following...
Overview of the useRef hook
The useRef hook in React is used to create a mutable object that persists across renders of a functional component.
React provides a useRef hook to create a ref:
const Title = () => {// Create a ref using useRefconst ref = useRef(null);// Render an h1 element with the ref attachedreturn <h1 ref={ref}>Hello World</h1>;}
Functional component using useRef to create a ref for an h1 element
The useRef hook takes an initial value as its only input argument and returns a ref object, putting that initial value under the current property.
There's no additional data structure required for useRef, other than the basic fiber hook support:
Just like useState and useEffect uses state to store the state and the effect, useRef uses state to store the ref. Next, let's take a look at how it's implemented.