13

In React quickstart, it is stated about Refs and Functional Components that

You may not use the ref attribute on functional components because they don't have instances:

function MyFunctionalComponent() {
  return <input />;
}

class Parent extends React.Component {
  render() {
    // This will *not* work!
    return (
      <MyFunctionalComponent
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

I don't fully understand the above statement and the example. So far from reading the tutorials, the only difference between functional and class component is that the latter can have things like constructor and lifecycle management functions.

What does the documentation mean when it says functional components don't have instances? Is it because they don't have this pointer? Is this restriction coming from react or ES6?

thor
  • 21,418
  • 31
  • 87
  • 173
  • 3
    Because they don't instantiate an object that inherits from their `.prototype`? As that is how "instance" is defined. – Bergi Jun 10 '17 at 22:54
  • @Bergi For `class Parent...` the declaration of `` is consider an instance, then for `function MyFunctionalComponent...` why isn't `` considered an instance. – user31782 Jun 11 '23 at 19:33
  • @user31782 `` is a jsx element, an object that instructs React to render the `MyComponent` component (regardless whether it's a function or a class). It is not an "instance". – Bergi Jun 12 '23 at 00:12

2 Answers2

4

React class components extend React.component which is a JS class. They are instances of React.component and inherit features like lifecycle hooks and internal state management from React.component itself. In this sense, I would call them components which have an instance, since React will use the same React.component instance to persist component state during its lifecycle.

React function components are nothing but JS functions: they get a set of properties as input and output a piece of virtual DOM. These functions are re-executed from top to bottom each time React decides the resulting virtual DOM might be out of date. Since plain JS functions don't persist any state by design, state persistence is delegated to a few global React API called hooks.

Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57
2

I faced the same doubt while reading the docs on ref. However, after doing a little more research I found this discussion. (https://github.com/facebook/react/issues/4936#issuecomment-142379068)

Functional components don't have instances because they are mere JS functions. A function can't have an instance. Whereas, classes have instances(objects) of them.

So when the documentation says you can't use ref on functional components because they don't have instances means that -> how can you store the instance of a functional component when it doesn't exist?

Vidur Singla
  • 265
  • 3
  • 12