Reputation: 13
I came across something like this in our codebase the other day I got curious. What, if any, is the difference between these methods of calling a function (that returns JSX) in the return method of a React component?
A.)
const TestXYZ = () => {
const TestFunc = () => {
return <div>This is some sample text</div>;
};
return (
<>
<TestFunc />
</>
);
};
B.)
const TestXYZ = () => {
const TestFunc = () => {
return <div>This is some sample text</div>;
};
return <>{TestFunc()}</>;
};
Thanks for your help!
Upvotes: 0
Views: 91
Reputation: 187262
This form has significant limitations:
<>{TestFunc()}</>
First of all, it cannot render class based components, only functional components.
But the bigger problem is that the render does not happen in the context of your view hierarchy. That means no hooks and no access to context.
For extra credit, let's desugar that syntax.
<TestFunc />
Transpiles to:
React.createElement(TestFunc, null)));
This says "React, here is a component, please render it for me". Note how we pass the component, but we don't call it. We let React do that for us.
And:
<>{TestFunc()}</>;
Transpiles to:
React.createElement(React.Fragment, null, TestFunc());
This says "React, here is some JSX I got from a function, please display it." Not how we execute the function ourself and just provide the result to React.
In one case your component is rendered in the context of your application with access to all the perks that offers, and in the other case it does not.
Upvotes: 1