useRef 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
T
required
The initial value to store in the ref object’s
.current property. Can be of any type. After initialization, you can mutate the .current property freely.Returns
Returns a mutable ref object with a single property:current: Initially set toinitialValue. You can read and write to this property. Changes to it do not cause re-renders.
Accessing DOM Elements
Storing Mutable Values
Keeping Previous Values
Avoiding Stale Closures
Measuring DOM Elements
Implementing Instance Variables
Tracking Render Count
Forwarding Refs
Debouncing with Ref
useRef is useful for more than just the ref attribute. It’s handy for keeping any mutable value around, similar to how you’d use instance fields in classes.Mutating the
.current property does not cause a re-render. If you need to trigger a re-render when a value changes, use useState instead.The ref object returned by
useRef is the same object on every render. It’s a plain JavaScript object that you can mutate freely.