thor
thor

Reputation: 22460

why do functional component in reactjs not have instances?

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?

Upvotes: 14

Views: 7643

Answers (2)

Andrea Carraro
Andrea Carraro

Reputation: 10419

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.

Upvotes: 4

Vidur Singla
Vidur Singla

Reputation: 305

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?

Upvotes: 2

Related Questions