What is the useRef hook?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid React.js basics — a prerequisite for any developer role.
Answer
useRef returns a mutable ref object whose .current property persists across renders without causing re-renders when changed. Two primary uses: (1) Accessing DOM elements: const inputRef = useRef(null); <input ref={inputRef} /> — after mounting, inputRef.current is the DOM input element. Use this to imperatively focus, scroll, or measure elements: inputRef.current.focus(). (2) Storing mutable values that persist across renders but do not trigger re-renders — unlike state. Use cases: storing previous state values, interval/timeout IDs for cleanup, debounce timers, tracking if a component is mounted. Example: const countRef = useRef(0); countRef.current++; — this increments but does NOT cause a re-render. Key difference from state: changing ref.current does not trigger a re-render; changing state does. Do not read or write refs during rendering — refs are for imperative operations. useRef(initialValue) only uses the initial value on the first render.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex React.js answers easy to follow.
Previous
What is the difference between controlled and uncontrolled components?
Next
What is the useContext hook?