What is a ref?
A ref is defined as any value that does not trigger a component re-render when it is changed.
A ref can be created with React.useRef()
hook or by the React.createRef()
function.
React.createRef
The React.createRef()
is a function that creates a new ref every time, it does not save its value between re-renders, instead creates a new instance of the ref for every re-render.
On class refs are created using React.createRef()
and attached to React elements via the ref attribute, are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
Accessing Refs
When a ref is passed to an element in render
, a reference to the node becomes accessible at the current attribute of the ref.
The value of the ref differs depending on the type of the node:
- When the ref attribute is used on an HTML element, the
ref
created in the constructor withReact.createRef()
receives the underlying DOM element as itscurrent
property. - When the
ref
attribute is used on a custom class component, theref
object receives the mounted instance of the component as itscurrent
.
React.useRef
The React.useRef()
is a hook that uses the same ref throughout, it saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render.
You can, however, use the ref attribute inside a function component as long as you refer to a DOM element.
Conclusion
The difference is that React.createRef()
will always create a new ref in a class-based component, React.useRef()
takes care of returning the same ref each time as on the initial rendering.