Callback Refs
Learn how you can get more precise control over when refs are set and unset.
We'll cover the following
What are Callback Refs?
A more flexible alternative to string refs is the callback refs. While being more flexible, their handling is slightly more cumbersome and must be managed explicitly. By using callback refs, it is possible to pass refs to a component’s child components and access their corresponding DOM elements.
As the name might suggest, callback refs are declared using the callback form. During mounting, they only receive a single parameter, the DOM element or, if applied to a React component, its
instance. We call the callback again during unmounting but with null
as a single parameter.
How you are specifically using callback refs is up to you. However, the convention is to save the reference to the DOM element as an instance property to access it from anywhere inside the component.
Code example
Applying this to our previous example from string refs, we end up with the following code:
Get hands-on with 1200+ tech skills courses.