When to use forwardRef ?
forwardRef example and explanation
Refs are the React way of accessing DOM elements, which is the counterpart for document.getElementById
and it’s equivalent methods.
But there is another concept called forwardRef
. In this article we will be going the explore the usage of this HOC.
If your are using React 16.2 and earlier then you should know this that it doesn’t yet support ref forwarding. In this case you have to pass the ref
as a regular prop
to the child component.
What is forwardRef?
A HOC provided by React. When a component is Wrapped in forwardRef
HOC, it does following things:
- provide a
ref
passed fromparent
component as a second argument in Component.
Note: The ref
argument, which is the second argument, it is only available when we wrap our component in forwardRef
HOC. It won’t exists if we don’t use forwardRef
.
Neither the props
contain any default prop with name ref
.
2. We can use this received ref
to bind it to any HTML DOM element, preferably the root element returned from component.
Usage of forwardRef in Class Components
Why forwardRef?
In order to pass down ref
from parent to child, in order to manipulate DOM for child component from parent component.
When to use forwardRef?
- When we want to alter the DOM of the child component without using any state variables.
- When we are developing any library and want to end user ability to attach their
refs
in order to manipulate the DOM. - forwardRef shines when used with useImperativeHandle.
https://rahuulmiishra.medium.com/useimperativehandle-hook-c9cdef239650
Apart from these there can be other use cases based on the requirements.
Example: Focusing input control, which is added as a child component.
Thanks for Reading.