Question presented to candidate:
"What does useRef give you, and when would you reach for it rather than state?"
What a strong answer should cover:
- It returns a mutable object with a
currentproperty that persists for the component's lifetime. - Writing to
.currentnever triggers a re-render. That is the defining property, and it is the feature rather than a limitation. - Two distinct use categories: DOM access (attach via the
refattribute) and instance values (timer ids, previous values, mutation flags, mutable caches). - The deciding question: does the UI need to update when this changes? Yes means state; no means a ref.
- Do not read
.currentduring render to decide output — it is not a reactive value, so the render can disagree with reality. useRef(initial)evaluates the initial value on every render even though it is only used once, so avoid expensive expressions there.- React 19:
refis a plain prop, and ref callbacks can return a cleanup function. - Related:
useImperativeHandlefor exposing a custom API rather than the raw node; a ref callback for measuring on attach.
Clarifying questions expected:
- "Does anything rendered depend on this value?" — that single question decides ref versus state.
Code / implementation expected: Yes — a DOM ref and an instance-value ref, ideally showing the render count not moving.