Is ForwardRef Necessary To Pass Down A React Ref
React
23/02/2023
Whenever you wish to pass down a ref
to a child component, React recommends to use forwardRef
. But why? Actually, you don't have to. As stated 📝 in React's (older) official documentation about forwarding refs:
Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries.
Therefore, you may pass down a ref
using any prop name, e.g. customRef={ref}
. There is no difference in terms of functionality. However, if you attempt to pass it down using the prop name ref
, you must use forwardRef
, otherwise you'll receive an error.
So why is ref
a reserved prop name? 🤔 The answer is to create a standardized and predictable API.
For instance, if you maintain a library, developers would need to be aware how they can pass down a ref
to your component. Keep in mind, this would require additional documentation. In fact, this was the case before the hook's introduction in React 16.3, when innerRef
had become a widely used convention.