The Ref attribute is a little bit like a key, in that it is a special React thing. It won't be applied to the DOM node that gets created, nor will it be passed as a prop if it’s use on a Component.
Instead, it signals to React that we want to do something special, and it works in many ways.
One way to use it, is to pass it a function and React will call this function for us, and provide us with the underlying DOM node.
<canvas
ref={function (canvas) {
console.log(canvas); // <canvas> DOM node
}}
width={200}
height={200}
/>
A more conventional way of using Ref attribute is to use the hook useRef
.
And the idea with refs is they’re like a box, and we can put whatever we want in the box, and React will persist this box across every render of the component so that we will always have access to it.
By default, useRef creates an object with a current property set to undefined. And like useState hook, I can pass an initial value if it pleases me, and then that will be what it initializes as.
But that doesn’t actually matter because almost immediately, I’m going to put the underlying ref inside that box. Let's take the example below.
function ArtGallery() {
// 1. Create a “ref”, a box that holds a value.
const canvasRef = React.useRef(); // { current: undefined }
return (
<main>
<div className="canvas-wrapper">
<canvas
// 2. Capture a reference to the <canvas> tag,
// and put it in the “canvasRef” box.
//
// { current: <canvas> }
ref={canvasRef}
width={200}
height={200}
/>
</div>
<button
onClick={() => {
// 3. Pluck the <canvas> tag from the box,
// and pass it onto our `draw` function.
draw(canvasRef.current);
}}
>
Draw!
</button>
</main>
);
}
This only runs when the component first renders, leading to improved performance. This is the conventional way to work with DOM node references in React!
The ref object created by the
useRef
hook should be thought of as a box. We can store whatever we want in this box: DOM nodes, numbers, arrays, objects, functions, etc... That said, the primary use case for refs is to store DOM nodes. It's pretty rare to need to store anything else in a ref.Here is the code sandbox from the code above:
🔍. Similar posts
React Component Cleanup
12 Mar 2025
How to Run Code on Mount in Your React Components Easily
04 Mar 2025
Best Practices for Using the useEffect Hook in React
22 Feb 2025