useRef is a React Hook that lets you reference a value that’s not needed for rendering.
Parameters
T
required
The value you want the ref object’s
current property to be initially. It can be a value of any type. This argument is ignored after the initial render.Returns
useRef returns an object with a single property:
T
Initially set to the
initialValue you passed. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property.On subsequent renders, useRef will return the same object.Changing the
ref.current property does not trigger a re-render. React is not aware of when you change it because a ref is a plain JavaScript object.Usage
Referencing a value with a ref
CalluseRef at the top level of your component to declare a ref:
Manipulating the DOM with a ref
It’s particularly common to use a ref to manipulate the DOM:- Input focus
- Scroll to element
- Video control
Avoiding recreating the ref contents
React saves the initial ref value once and ignores it on subsequent renders:Common Use Cases
Storing timeout/interval IDs
Tracking previous value
Storing mutable values
Measuring DOM elements
Accessing latest props in callbacks
TypeScript
Ref with initial value
Custom ref types
Troubleshooting
I can’t get a ref to a custom component
By default, you can’t pass refs to custom components:forwardRef to enable refs:
My ref.current is null
This happens before the component mounts:Changing ref.current doesn’t re-render
This is expected behavior. If you need re-renders, useuseState instead:
Should I use ref or state?
UseuseState when:
- The value is displayed in the UI
- Changes should trigger re-renders
- You need React to “react” to changes
useRef when:
- Storing values that don’t affect rendering
- Accessing DOM elements
- Keeping mutable values across renders
- Storing timeout/interval IDs