Interview frequency: …
Short answer
useRef stores mutable values for the component's lifetime without causing a Re-render when they change, and also provides direct access to DOM nodes.
Explanation
A ref is an ordinary JavaScript object with a .current property. Changing ref.current does not notify React, so it does not cause a new render. It can store Timer IDs and previous state values, or control focus and media directly in DOM elements.
Code example
function TextInputWithFocusButton() {
const inputEl = useRef<HTMLInputElement>(null);
const onButtonClick = () => {
// Direct access to the DOM element and focus the cursor
inputEl.current?.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the cursor</button>
</>
);
}Common mistakes
- Reading or writing ref.current during Render instead of in event handlers or Effects.