JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
mid
hooks

What is useRef and when should you use it?

useRef
hooks
dom
mutable-values
refs
Quick Answer

useRef creates a mutable reference that persists across renders without causing re-renders when changed. Use it for accessing DOM elements, storing mutable values that don't need to trigger updates, and keeping references to timers or previous values.

Detailed Explanation

What useRef Does:

  • Returns a mutable ref object with .current property
  • Value persists across re-renders
  • Changing .current doesn't trigger re-render
  • Same ref object is returned every render

Use Cases:

  1. DOM Access: Focus inputs, measure elements, scroll
  2. Mutable Values: Timers, intervals, previous values
  3. Instance Variables: Values that shouldn't trigger render
  4. External Libraries: Integration with non-React code

useRef vs useState:

  • useState: Value changes trigger re-render
  • useRef: Value changes don't trigger re-render

useRef vs createRef:

  • useRef: Same object across renders (hooks)
  • createRef: New object each render (class components)

Code Examples

DOM element access
function TextInput() {
  const inputRef = useRef(null);
  
  const focusInput = () => {
    inputRef.current.focus();
  };
  
  const selectAll = () => {
    inputRef.current.select();
  };
  
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus</button>
      <button onClick={selectAll}>Select All</button>
    </div>
  );
}

// Scrolling to element
function ScrollToTop() {
  const topRef = useRef(null);
  
  const scrollToTop = () => {
    topRef.current.scrollIntoView({ behavior: 'smooth' });
  };
  
  return (
    <div>
      <div ref={topRef} />
      {/* ... lots of content ... */}
      <button onClick={scrollToTop}>Back to Top</button>
    </div>
  );
}

Resources

React Docs - useRef

docs

React Docs - Manipulating the DOM with Refs

docs

Related Questions

What are custom hooks and how do you create them?

mid
hooks
Previous
What are custom hooks and how do you create them?
Next
What is the difference between controlled and uncontrolled components in React forms?