What is the difference between useState and useRef in React?

What is the difference between useState and useRef in React?

What is the difference between useState and useRef in React?

Question

What is the difference between useState and useRef in React?

Answer

useState

Stores state that, when changed, triggers a re-render of the component. Use it for any value that should be reflected in the UI.

const [count, setCount] = useState(0);

return (
    <button onClick={() => setCount(c => c + 1)}>
        Clicked {count} times
    </button>
);

useRef

Stores a mutable value in a .current property that persists across renders without causing re-renders. Primarily used for two purposes:

  1. DOM references — access a DOM element directly
  2. Mutable values — store timers, previous values, or flags without triggering re-renders
// DOM reference
const inputRef = useRef(null);
const focusInput = () => inputRef.current.focus();
return <input ref={inputRef} />;

// Mutable value — store interval ID without re-rendering
const timerRef = useRef(null);
const start = () => { timerRef.current = setInterval(tick, 1000); };
const stop  = () => clearInterval(timerRef.current);

Quick Comparison

useStateuseRef
Triggers re-renderYesNo
MutableVia setter onlyDirectly via .current
Use forUI stateDOM refs, timers, flags
All Comments