Refs in React — React Technical Interview Questions & Answers
Refs in React
Refs in React
- A ref is a box that holds a mutable value without causing a re-render. useRef(null) then ref={el} on an input. After mount, el.current is the DOM node — focus(), scrollIntoView(), measure width. That’s the main UI use.
- You can also keep a timer id or previous value in ref.current. Updating a ref does not re-render. If the screen must change, that’s state, not a ref. Mixing them: store a value in ref and wonder why the p tag didn’t update — classic trap.
- Refs in React — on mount the name box gets focus. ref.current is the real input.
Technical Interview Tip: DOM escape hatch. Not a state replacement.
Code Examples for Refs in React
Example
// Refs
import { useRef, useEffect } from "react";
export default function Focus() {
const input = useRef(null);
useEffect(() => {
input.current.focus();
}, []);
return <input ref={input} placeholder="Name" />;
}
Refs in React — on mount the name box gets focus. ref.current is the real input.
How to Explain Refs in React to an Interviewer
Does changing ref.current re-render?
No
Give one valid ref use.
Focus an input