Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are React Functional Components Regular Functions or Constructor Functions?

In olden times (in other words, a few years ago) React Components were classes with a render method.

class MyComponents extends React.Component {
    render() {
        return <div>...</div>
    }
}

In more recent times, React's introduced functional components.

function MyComponent() {
    return <div>...</div>
}

Either of the above would let you use your component in another bit of JSX -- something like this

<Navigation>
    <MyComponent/>
</Navigation>    

I'd like to know if, behind the scenes, React is using these functional component functions as object constructors or is it just calling the component function as a regular function.

That is -- you can call a javascript function

function someFunction() {
    //...
}

const result = someFunction()

Or, you can use a javascript function to create a new object

function SomeFunction() {
    //...
}

const object = new SomeFunction()        

In plain javascript the convention is usually that a function that's Capitalized is a constructor function, and function that's not is a regular function. However, a lot of the shallow blog articles I read on components indicate (but never state outright) that these component functions are used as regular functions and not as object constructors.

Does anyone here know whether functional components are object constructors, regular functions, or if React's doing some third weird thing behind the scenes. Bonus points if you can point out the particular bit(s) of React's internal code that's doing this.

like image 490
Alan Storm Avatar asked Aug 13 '26 08:08

Alan Storm


1 Answers

OK, I think I've tracked this one down conclusively. Functional Components are not invoked as constructor-functions -- they're just called as regular function.

First -- if I add some debugging to a component

    function MyComponent() {
        /* ... */
        console.log(this)
        /* ... */
    }

the value of this is undefined. That's consistent with code calling MyComponent as a function. If code invoked new MyComponent, this would be an instance of a MyComponent object.

Second, if I'm reading the source right, it looks like this conditional is one place where React has branching logic for dealing with class-based vs. function-based components.

A class based component gets the new treatment, but a function based component does not.

    if (isClass) {
      inst = new Component(element.props, publicContext, updater);
      /*...*/
    } else {
      /* ... */
      inst = Component(element.props, publicContext, updater);
      /* ... */
    }       
like image 150
Alan Storm Avatar answered Aug 15 '26 22:08

Alan Storm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!