Facebook Pixel

How to Access DOM Elements in React With useRef

Accessing the DOM directly is sometimes necessary. Here is how to do it safely with useRef in React.

How to Access DOM Elements in React With useRef

Sometimes you need direct DOM access, like focusing an input or measuring an element. Here is how to do it safely with useRef.

Create a Ref

Call useRef with an initial value of null to create a ref. This gives you a mutable object whose current will hold the DOM node.

Attach the Ref

Pass the ref to an element as the ref prop. After the element mounts, ref.current points to the real DOM node.

Use the Ref in Effects

Read or manipulate the DOM in useEffect, not in the render body. During render, the element may not be mounted yet, so ref.current could be null.

Common Use Cases

Focusing an input on mount, measuring an element's size with getBoundingClientRect, integrating with a non-React library, or scrolling to a position are all common DOM-access use cases.

Avoid Overusing Refs

React prefers you avoid direct DOM manipulation. Most UI updates should go through state and props. Use refs only when state and props cannot do the job, like focusing or measuring.

Clean Up If Needed

If you set up something on the DOM node, like a non-React library that attaches listeners, clean it up in the effect's return function.

The Takeaway

Use useRef to access a DOM element: create a ref, attach it, and read or manipulate ref.current in useEffect. Use it only when state and props cannot do the job, and clean up anything you set up.

Call useRef with null to create a ref, attach it to an element with the ref prop, and read or manipulate ref.current in useEffect. The ref persistently holds the DOM node after the element mounts.

Because during render, the element may not be mounted yet, so ref.current could be null. In useEffect, the element is guaranteed to be mounted, so you can safely read or manipulate the DOM node.

Focusing an input on mount, measuring an element's size with getBoundingClientRect, integrating with a non-React library, and scrolling to a position. These need direct DOM access that state and props cannot provide.

No. React prefers you avoid direct DOM manipulation. Most UI updates should go through state and props. Use refs only when state and props cannot do the job, like focusing or measuring, to avoid fighting React.

If you set up something on the DOM node, like a non-React library attaching listeners, return a cleanup function from useEffect that tears it down. This prevents leaks when the component unmounts.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.