Facebook Pixel

useRef vs useState: When to Use Which in React

useRef and useState both persist values, but they behave very differently. Here is how to choose.

useRef vs useState: When to Use Which in React

useRef and useState both persist values across renders, but they behave very differently. Here is how to choose.

The Key Difference

useState triggers a re-render when it changes. useRef does not. This single difference determines which to use.

When to Use useState

Use useState for values that should drive the UI. Counters, form values, toggles, fetched data, anything where a change should update what the user sees.

When to Use useRef

Use useRef for values that should persist without triggering re-renders. DOM references, timer ids, previous values, flags for whether the component is mounted, and integration with non-React code.

The Mental Model

useState is for reactive state: changing it tells React to re-render. useRef is for instance-like values: persistent across renders but invisible to the render cycle.

A Common Mistake

Storing a value in useRef that should drive the UI, then wondering why the UI does not update. If the UI should react to a change, it belongs in useState.

Another Common Mistake

Storing a timer id in useState, which causes unnecessary re-renders when the id changes. Timer ids and similar internal values belong in useRef.

The Takeaway

Use useState for values that should trigger re-renders and drive the UI. Use useRef for values that should persist across renders without triggering re-renders. The key question is: should changing this value update the UI?

useState triggers a re-render when it changes. useRef does not. Use useState for values that should drive the UI, and useRef for values that should persist without triggering re-renders.

For values that should persist across renders but should not trigger re-renders: DOM references, timer ids, previous values, mounted flags, and integration with non-React code. If the UI should react to a change, use useState instead.

Because useRef does not trigger re-renders. If a value should drive the UI, it belongs in useState, not useRef. Using useRef for UI state is a common mistake that leaves the UI out of sync.

useRef. Timer ids do not need to trigger re-renders, so storing them in useState causes unnecessary re-renders when the id changes. useRef lets you persist the id without affecting the render cycle.

Ask: should changing this value update the UI? If yes, use useState so React re-renders. If no, use useRef so the value persists without triggering a re-render.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.