Lesson 12 of 20

useRef Hook

References with useRef

useRef creates a mutable reference that persists across renders without causing re-renders when changed. It's commonly used to access DOM elements directly and to store values that don't need to trigger updates.

Unlike state, changing a ref's .current value does not cause the component to re-render.

Example
import { useRef, useState, useEffect } from 'react';

function SearchInput() {
  const inputRef = useRef(null);
  const renderCount = useRef(0);
  const [query, setQuery] = useState('');

  // Focus the input on mount
  useEffect(() => {
    inputRef.current.focus();
  }, []);

  // Track renders without causing re-renders
  useEffect(() => {
    renderCount.current += 1;
  });

  return (
    <div>
      <input
        ref={inputRef}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search..."
      />
      <p>Renders: {renderCount.current}</p>
      <button onClick={() => inputRef.current.focus()}>
        Focus Input
      </button>
    </div>
  );
}
  • useRef(initialValue) — Creates a ref with .current property
  • Attach to DOM elements with the ref attribute
  • Access the DOM node via ref.current
  • Changes to .current don't trigger re-renders
  • Useful for: focus management, timers, previous values, DOM measurements
Notes
  • Use refs sparingly for DOM access. Most of the time, you can handle things declaratively with state and props. Refs are an escape hatch for when you need direct DOM access.