Skip to main content

useRef for accessing a DOM element

What useRef does with the DOM

The useRef() hook lets you get a direct reference to a DOM element rendered by a component. It is an analog of the old document.querySelector(), but reactive and safe - React itself assigns the reference on mount.


Steps to use useRef for DOM access

1. Import the hook

javascript
import { useRef, useEffect } from "react";

2. Create a ref inside the component

javascript
const inputRef = useRef(null);

Here inputRef.current will initially be null, but after the render React automatically fills it with a reference to the real DOM element.

3. Pass the ref into JSX

javascript
<input ref={inputRef} />

4. Use .current after mounting

(for example, inside useEffect, so the element already exists in the DOM)

javascript
useEffect(() => { inputRef.current.focus(); // focuses the input }, []);

Full example

javascript
import { useRef, useEffect } from "react"; function InputFocusExample() { const inputRef = useRef(null); useEffect(() => { // Once the component has mounted, the input already exists in the DOM inputRef.current.focus(); }, []); return ( <div> <input ref={inputRef} placeholder="I will be focused on load" /> <button onClick={() => inputRef.current.focus()}> Focus again </button> </div> ); }

What happens here:

  1. React renders the <input>.
  2. It binds it to inputRef.current.
  3. After the render (useEffect) you can use any DOM methods:
  • .focus()
  • .scrollIntoView()
  • .select()
  • .play() (for video/audio)
  • etc.

Example with scrolling

javascript
function ScrollToBottom() { const endRef = useRef(null); const scrollToBottom = () => { endRef.current.scrollIntoView({ behavior: "smooth" }); }; return ( <div style={{ height: 200, overflowY: "scroll", border: "1px solid #ccc" }}> <div style={{ height: 600 }}>Content...</div> <div ref={endRef}>End of list</div> <button onClick={scrollToBottom}>Scroll down</button> </div> ); }

Important to remember

FeatureExplanation
ref.current is initially nullbecause the DOM has not been created yet before the first render
Use ref.current only after mountinginside useEffect
Changing ref.current does not trigger a renderReact does not track it
A ref can be passed into any JSX element or a custom component with forwardRefto forward it inward

Summary

QuestionAnswer
What does useRef do with the DOMGives a reference to the real DOM element after render
How to use itCreate const elRef = useRef(null) → pass ref={elRef} → access elRef.current
When to access itAfter mounting (useEffect)
What you can doFocus, scroll, resize, call DOM methods

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.