Reputation: 22304
I already understand the Difference between React Component and React Element, that using JSX basically calls React.createElement
which returns an element, e.g.:
const element = <Component />
However, what happens when I call a Component as a function?
const whoAmI = Component()
I have seen the 2 approaches in code from multiple developers similar to following (oversimplified):
class Big extends React.PureComponent {
renderSomething() { return <div>something</div> }
render() {
const helper = () => <div>{x}</div>
return <>
{this.renderSomething()}
{helper()}
<this.renderSomething />
<helper />
</>
}
}
Are these identical or what's the difference?
Upvotes: 7
Views: 1328
Reputation: 22304
There is a difference in number of elements created:
<Fn />
creates an intermediate element, the "Fn" itself
(i.e. it mounts and renders the "Fn" Component)
Fn()
just uses the return value of the function called "Fn"
("Fn" is not actually a React Component, just a function that returns a React Element)
This can be visible in the React Developer Tools, similar to following:
<Big>
<div>something</div>
<div>1</div>
<this.renderSomething>
<div>something</div>
<this.renderSomething>
<helper>
<div>2</div>
<helper>
</Big>
For more details on how React works: https://overreacted.io/react-as-a-ui-runtime/.
Upvotes: 5