What is the difference between useState and useRef in React?
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>
);
Stores a mutable value in a .current property that persists across renders without causing re-renders. Primarily used for two purposes:
// 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);
| useState | useRef | |
|---|---|---|
| Triggers re-render | Yes | No |
| Mutable | Via setter only | Directly via .current |
| Use for | UI state | DOM refs, timers, flags |
All Comments