...

/

Understanding the useRef Hook Design

Understanding the useRef Hook Design

Learn how React creates a ref for direct DOM interaction.

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 useRef
const ref = useRef(null);
// Render an h1 element with the ref attached
return <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:

Press + to interact
useRef design
useRef design

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. ...