Key Differences Between useState and useRef
- Re-rendering Behavior:
- useState triggers a re-render whenever the state is updated. This is ideal for values that affect the UI, as any change should reflect immediately.
- useRef, on the other hand, holds a mutable value that doesn’t cause a re-render when it changes. It’s best suited for values that don’t need to trigger re-renders (e.g., timers, input values during an input field focus, or holding a DOM reference)
- Persistent Value Across Renders:
- Both useState and useRef retain values between renders. However, useRef keeps the same object reference, meaning it doesn’t reset between renders unless you explicitly change it, whereas useState is a value-based approach and provides a new reference with each update, causing a re-render
- Why Not an Extra Parameter for useState?
- Adding an extra parameter to useState (like reRender: true/false) could make the API more complex and harder to understand, as useState is intended specifically for reactive state that affects the UI.
- useRef serves a different purpose: maintaining a mutable reference without triggering re-renders. Overloading useState with non-reactive values could lead to confusing code and unintended side effects.
When to Use useRef vs. useState?
- Use useState when the data is part of the render flow and needs to update the UI
- Use useRef when you want to store a value that doesn’t need to trigger a re-render, like a value you just want to persist across renders
In summary, useState and useRef are designed with different purposes in mind, and React keeps them separate to maintain clarity. By using useRef for non-reactive data, you avoid unintended re-renders, keeping your app more efficient