QA
Beginner LevelReact JS & React 19

What is the useRef hook and how does it differ from useState?

❓ Interview Prompt: Explain useRef, `ref.current`, accessing DOM elements, persisting mutable values across renders without triggering re-renders.

'useRef' returns a mutable ref object whose '.current' property is initialized to the passed argument. The ref object persists across re-renders.

Differences from 'useState':

1
No Re-Renders: Updating 'ref.current = newValue' does NOT trigger a component re-render!
2
Synchronous Updates: 'ref.current' updates synchronously and is available immediately.

Primary Use Cases:

•
Direct access to DOM nodes ('inputRef.current.focus()').
•
Storing mutable timer IDs, interval handles, or previous state values.

Code Implementation Example

jsx
function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    // Access raw DOM node directly!
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus Input</button>
    </>
  );
}
💡Accessing DOM nodes directly using useRef.
🎯 Interview Key Takeaway

useRef stores mutable values across renders without triggering component re-renders.

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?