Problem:
I have written this code in my React which is a wrapper component to condition show something
const AccessControl = ({ content, children }: acProps) => {
return content ? children : null;
};
<AccessControl content={order.location.messageInternal}>
<Grid md={12} className="result-three-block padding" p={0.1}>
<p>{order.location.messageInternal}</p>
</Grid>
</AccessControl>
I can also do in this way
{order.location.messageInternal && <Grid md={12} className="result-three-block padding" p={0.1}>
<p>{order.location.messageInternal}</p>
</Grid>}
This is all happening inside a map function which is loading with 20 limit data.
So is it any performance issue in using wrapper component or with conditions within a component.
Solution:
Let’s show your two snippets to Babel (v. 7.23.2; targets: defaults, not ie 11, not ie_mob 11
; presets: react
/typescript
).
The first one is transpiled into the same function and a _jsx()
call:
const AccessControl = ({ content, children }) => {
return content ? children : null;
};
/*#__PURE__*/ _jsx(AccessControl, {
content: order.location.messageInternal,
children: /*#__PURE__*/ _jsx(Grid, {
md: 12,
className: "result-three-block padding",
p: 0.1,
children: /*#__PURE__*/ _jsx("p", {
children: order.location.messageInternal
})
})
});
The second also has a _jsx()
call (note that I wrapped it in a Fragment
, so only the inner one counts):
/*#__PURE__*/ _jsx(_Fragment, {
children:
order.location.messageInternal &&
/*#__PURE__*/ _jsx(Grid, {
md: 12,
className: "result-three-block padding",
p: 0.1,
children: /*#__PURE__*/ _jsx("p", {
children: order.location.messageInternal
})
})
});
Due to JS’s short circuitry behaviour, it will skip _jsx(Grid, /* ... */)
as soon as order.location.messageInternal
is determined as falsy. This is quite clear, even in the original source code.
Meanwhile, the first snippet evaluates the property values, both order.location.messageInternal
and _jsx(Grid, /* ... */)
, before passing them to the outer _jsx()
:
/*#__PURE__*/ _jsx(AccessControl, { // Step 3: Pass the object to the outer call
content: order.location.messageInternal, // Step 1: Evaluate order.location.messageInternal
children: /*#__PURE__*/ _jsx(Grid, { /* ... */ }) // Step 2: Call _jsx(...)
});
Statically speaking, the second is potentially faster than the first. However, the difference in performance might not even worth noticing if your app doesn’t do hundreds to thousands of these updates every second or so. See also this video on the topic of premature optimization by CodeAesthetic.
Readability-wise, the second is worse, although the first is not really clear either. If you want some general suggestions on your code, check out our sister site Code Review.