Why can't you pass a ref to a functional component in react?
What is different in function components compared to class components that you can't pass a ref to it?
Why is that not possible?
Notes: I'm making this question, because I always saw explanations about how to use ref with functional components, and that you need to use fowardRef, but no one explained how react handles functional components making it not possible to pass a ref to it, it's always explained how to do it, but never why you need to do it.
When you pass ref to a class component, it's made to point (via ref.current) to the actual class instance. (See "Accessing Refs" in the legacy React documentation.) That lets you access the fields of that instance. But function components don't have instances or fields, so there's nothing for ref to point to, and nothing it could be used for.
And, to be clear, forwardRef doesn't really change that. forwardRef still doesn't let ref point to the instance, because there still isn't one. Instead, forwardRef lets you "forward" the ref to another object: either a nested component (typically a DOM element), or a custom object that you define (using useImperativeHandle).
Presumably, if React were being designed from scratch today, ref would be done a bit differently. But because of its history — because it has a special meaning for class components — ref is reserved.
You can, however, use another prop name like innerRef and use it for forwarding, as discussed at Why, exactly, do we need React.forwardRef?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With