Why you can't pass a ref to a functional component in react?

Viewed 2382

Why you can't 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.

1 Answers

There are two aspects:

  • Function components don't have ref attribute because they don’t have instances like class components. Therefore you must FORWARD THE REF to any other element within it.
  • You can't use the ref prop as it reserved.

You can, however, use another prop name like innerRef and use if for forwarding.

Check a more detailed answer with examples: Why, exactly, do we need React.forwardRef?.

Related