useRef vs useState in React
Both useRef and useState are React hooks, but they serve different purposes and have different performance characteristics.
useRef
useRef is used to update values very fast in real-time but doesn't refresh the UI.
Key characteristics:
- Updates values faster than useState
- Doesn't trigger re-renders
- Helpful for frequently updated values
- Reduces latency for real-time updates
Use cases:
- DOM element references
- Storing mutable values that don't need to trigger re-renders
- Timers and intervals
- Previous values storage
const countRef = useRef(0);
// This won't trigger a re-render
countRef.current = countRef.current + 1;
useState
useState updates values slightly slower than useRef because it also re-renders the UI every time it updates.
Key characteristics:
- Triggers component re-renders
- Updates are reflected in the UI
- Slower than useRef due to re-rendering
- Standard for reactive state management
Use cases:
- Counters that need to display updates
- Form inputs
- Any state that affects the UI
- Text previews and dynamic content
const [count, setCount] = useState(0);
// This triggers a re-render and updates the UI
setCount(count + 1);
When to Use Which?
- useRef: For values that change frequently but don't need to update the UI
- useState: For values that need to be displayed or affect the component's rendering
Choose based on whether you need the UI to react to changes or just need to store/update values efficiently.