Reputation: 53
This is something that makes sense in my head but I haven't been able to find any facts/articles to back this up.
Essentially is doing something like
render() {
return (
someBoolean && <div>Some Markup</div>
)
}
less performant than
render() {
return (
someBoolean && <SomeComponent />
)
}
where SomeComponent
has the same exact markup as the previous example.
My reasoning is since the markup will have to be created on every re-render it'll take up more memory whereas the saved component SomeComponent
will be referenced in memory and won't have to be created on every re-render.
Is there somewhere in the react docs that explains this more thoroughly?
Or is this reasoning not accurate?
Upvotes: 5
Views: 202
Reputation:
Whether it's conditional or not is not an issue, as neither will be evaluated past the &&
if someBoolean
is false.
The real question is whether a defined React subcomponent has a performance advantage or penalty versus plain JSX markup defined within another component. For practical purposes, there is no performance difference unless you are making use of custom functions for lifecycle hooks.
For example, if you use a subcomponent, you may define a separate shouldComponentUpdate
method within that component and thereby decouple its updates from the parent. In the case of plain JSX, it will update as part of the parent component.
Upvotes: 1
Reputation: 223104
JSX is syntactic sugar for React.createElement
. As it can be seen in Babel REPL, they are
return someBoolean && React.createElement(
"div",
null,
"Some Markup"
);
and
return someBoolean && React.createElement(SomeComponent, null);
respectively.
When someBoolean
is falsy, React.createElement
isn't called and render
becomes no-op.
SomeComponent
isn't cached, it is re-created every time. In comparison with raw markup, it provides negligible overhead, considering that it is a stateless component:
const SomeComponent = () => <div>Some Markup</div>;
Both options are very fast and aren't supposed to be optimized.
Upvotes: 4