Q10: What is useRef and how does it differ from useState?

useRef returns a mutable object { current: initialValue } whose reference persists across re-renders. Modifying ref.current does not trigger a component re-render. It is used to access direct DOM nodes or store instance variables that shouldn't cause UI updates when mutated.

DOM Focus Control with useRef
function TextInputWithFocus() {
  const inputEl = useRef(null);
  
  const onButtonClick = () => {
    // Imperative focus targeting
    inputEl.current.focus();
  };
  
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus Input</button>
    </>
  );
}
💡 inputEl.current references the underlying native HTMLInputElement node directly.
Key Takeaways
  • Mutating .current updates values synchronously without causing a re-render.
  • Commonly used for imperative DOM access (focus, canvas, media playback) and timer IDs.
Knowledge Check

What happens to the UI component when you assign timerRef.current = setTimeout(...) inside a click handler?