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:
- React renders the
<input>. - It binds it to
inputRef.current. - 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
| Feature | Explanation |
|---|---|
ref.current is initially null | because the DOM has not been created yet before the first render |
Use ref.current only after mounting | inside useEffect |
Changing ref.current does not trigger a render | React does not track it |
A ref can be passed into any JSX element or a custom component with forwardRef | to forward it inward |
Summary
| Question | Answer |
|---|---|
What does useRef do with the DOM | Gives a reference to the real DOM element after render |
| How to use it | Create const elRef = useRef(null) → pass ref={elRef} → access elRef.current |
| When to access it | After mounting (useEffect) |
| What you can do | Focus, scroll, resize, call DOM methods |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.