Value of Using React.forwardRef vs Custom ref Prop
When working with React, you may come across situations where you need to pass a ref from a parent component to a child component. This is where the ref
prop comes into play. However, React provides two different approaches to achieve this: using React.forwardRef
or creating a custom ref
prop. In this blog post, we will explore the value of using React.forwardRef
over a custom ref
prop.
Using a Custom ref Prop
One way to pass a ref from a parent component to a child component is by creating a custom ref
prop. This involves manually passing the ref
from the parent component to the child component.
Here’s an example of how you can use a custom ref
prop:
// ParentComponent.js
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const childRef = useRef(null);
return (
);
}
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = React.forwardRef((props, ref) => {
return (
{/* Child component content */}
);
});
export default ChildComponent;
In the above example, we create a custom ref
prop called childRef
in the parent component and pass it to the ChildComponent
using the ref
prop. Inside the ChildComponent
, we use React.forwardRef
to forward the ref
to the underlying DOM element.
Using React.forwardRef
React provides a built-in utility called React.forwardRef
that simplifies the process of passing a ref from a parent component to a child component. It allows you to forward the ref
automatically without manually creating a custom ref
prop.
Here’s how you can use React.forwardRef
:
// ParentComponent.js
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const childRef = useRef(null);
return (
);
}
export default ParentComponent;
// ChildComponent.js
import React from 'react';
const ChildComponent = React.forwardRef((props, ref) => {
return (
{/* Child component content */}
);
});
export default ChildComponent;
In the above example, we use React.forwardRef
to wrap the ChildComponent
and automatically forward the ref
to the underlying DOM element. This eliminates the need to manually create a custom ref
prop.
Conclusion
Both using a custom ref
prop and React.forwardRef
are valid approaches for passing a ref from a parent component to a child component. However, React.forwardRef
provides a more streamlined and concise way to achieve this, eliminating the need for manual prop passing.
By using React.forwardRef
, you can keep your codebase cleaner and more maintainable, especially when dealing with complex component hierarchies.
Leave a Reply