What is the useRef hook?
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.
Previous
What is the difference between controlled and uncontrolled components?
Next
What is the useContext hook?