Overview
TheuseRef hook returns a mutable ref object whose .current property is initialized to the passed argument. The returned object persists for the full lifetime of the component.
Signature
Parameters
The initial value for the
ref.current property. This value is only used on the first render.Returns
A mutable ref object with a single property:The
current property can be mutated directly and persists across re-renders.Usage Examples
Storing DOM References
Storing Mutable Values
Use refs to store values that don’t trigger re-renders when changed:Tracking Previous Values
Avoiding Re-renders
Unlike state, updating a ref does not trigger a re-render:Storing Callbacks
Key Differences from State
| Feature | useRef | useState |
|---|---|---|
| Triggers re-render | No | Yes |
| Mutable | Yes (via .current) | No (immutable) |
| Persistence | Across renders | Across renders |
| Use case | DOM refs, mutable values | UI state |
Rules and Behavior
- Persistent across renders - The same ref object is returned on every render
- Mutable - You can mutate
ref.currentdirectly without causing re-renders - Initialization - The initial value is only used on the first render
- No re-render - Changing
ref.currentdoes not trigger a re-render - Must be called at top level - Don’t call
useRefinside loops, conditions, or nested functions - Only in functional components - Cannot be used in class components
Common Use Cases
- Accessing DOM elements directly
- Storing interval or timeout IDs
- Keeping track of previous state values
- Storing mutable values that shouldn’t trigger re-renders
- Caching callback functions
- Storing instance variables in functional components
Implementation Details
- Returns the same object reference (
{ current: value }) across all renders - Stored in the component’s hooks data structure
- Does not trigger any re-render mechanism when
.currentis modified - The ref object itself never changes, only its
.currentproperty can be mutated