Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Understanding useRef Hook in React

Learn how to use useRef to access DOM elements and persist values across renders.

jiocoder TeamUpdated Jun 6, 20261 min readReact
Understanding useRef Hook in React

What is useRef?#

useRef returns a mutable ref object whose .current property is initialized to the passed argument. The returned object will persist for the full lifetime of the component.

Accessing DOM Elements#

Code
import { useRef } from 'react';

function TextInput() {
  const inputRef = useRef(null);
  
  const handleClick = () => {
    inputRef.current.focus();
  };
  
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

Storing Mutable Values#

Code
function Timer() {
  const [count, setCount] = useState(0);
  const intervalRef = useRef(null);
  
  const startTimer = () => {
    intervalRef.current = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
  };
  
  const stopTimer = () => {
    clearInterval(intervalRef.current);
  };
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={startTimer}>Start</button>
      <button onClick={stopTimer}>Stop</button>
    </div>
  );
}

Previous Value Tracking#

Code
function Counter() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();
  
  useEffect(() => {
    prevCountRef.current = count;
  });
  
  const prevCount = prevCountRef.current;
  
  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
    </div>
  );
}

Key Differences from useState#

  • useRef doesn't trigger re-renders when changed
  • useRef persists across renders
  • useRef.current is mutable
  • useState triggers re-renders and is immutable

Best Practices#

  • Use useRef for DOM access when needed
  • Store mutable values that don't need to trigger renders
  • Don't read or write ref.current during render
  • Use refs sparingly - prefer state for most cases

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment