davidatthepark
davidatthepark

Reputation: 1365

When using the same React component multiple times, is it more performant to assign it to a variable?

<div>
  <SomeComponentWithProps propA={'some prop'} propB={'some other prop'} >
  <SomeComponentWithProps propA={'some prop'} propB={'some other prop'} >
</div>

Is there a performance benefit to refactoring the above code to:

const someComponent = <SomeComponentWithProps propA={'some prop'} propB={'some other prop'} >
<div>
   {someComponent}
   {someComponent}
</div>

Would the assigned component be rendered and cached?

Upvotes: 2

Views: 1302

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

Is there a performance benefit to refactoring the above code to:

In theory yes, since you are calling React.createElement only once. But whether it makes a noticeable difference in your application is another question. Most likely not.

Would the assigned component be rendered and cached?

tl;dr: No.

React.createElement basically returns a component "descriptor". The component is not instantiated or rendered at that point. We can easily test this (note that there is no console output from the constructor):

class Foo extends React.Component {
  constructor() {
    super();
    console.log('inside constructor');
  }
 
  render() {
    return 'Foo';
  }
}

const component = <Foo />;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Lets look at the component descriptor:

function Foo({bar}) {
  return <span>{bar}</span>;
}

console.log(<Foo bar={42} />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

You can see, all the React.createElement returns is an object that holds information about which function to call, the props to pass and some meta data information.

The actual rendering happens later.

Upvotes: 4

Related Questions