MyInternships.in

React Hooks

React useRef Hook

useRef returns a mutable object with a single current property that survives re-renders. Changing current does not trigger a render, which makes refs useful both for reaching DOM nodes and for storing values that should not cause updates.


What is useRef Hook in React?

useRef returns a mutable object with a single current property that survives re-renders. Changing current does not trigger a render, which makes refs useful both for reaching DOM nodes and for storing values that should not cause updates.

Why useRef Hook matters

Some things are outside React’s data flow: focusing an input, measuring an element, keeping a timer id, remembering the previous value. Refs are the escape hatch for exactly those cases.

useRef Hook example

A ref pointing at a DOM node
JSX
function SearchBox() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();   // available after the DOM is committed
  }, []);

  return <input ref={inputRef} placeholder="Search internships" />;
}

How this works

React assigns the DOM node to inputRef.current after commit, so the ref is null during the first render and populated by the time effects run.

A ref as an instance variable

JSX
const timerRef = useRef(null);

function start() {
  timerRef.current = setInterval(tick, 1000);   // no re-render
}
function stop() {
  clearInterval(timerRef.current);
}

The interval id must survive renders but should not cause one. That is exactly what a ref is for — state would trigger a pointless re-render.

useRef vs useState

useRefuseState
Triggers re-render on changenoyes
Value survives rendersyesyes
Read during renderdiscouragedyes, that is the point
Typical useDOM nodes, timer ids, previous valuesanything shown on screen

Common mistakes with useRef Hook

  • Storing something the UI displays in a ref, so the screen never updates.
  • Reading ref.current during the first render, when it is still null.
  • Mutating a ref during render instead of in an effect or event handler.

React useRef Hook— Interview Questions & FAQs

What is the difference between useRef and useState?+

Both persist across renders, but changing a ref does not re-render the component. Use state for anything the user sees, and a ref for values the render output does not depend on.

Why is my ref null?+

Refs are attached after the DOM is committed. Read ref.current inside useEffect or an event handler, never during the render pass.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships