What is difference in writing in two different ways below?
function App(isTrue){
if(isTrue)
return <ComponentA/>
else
return <ComponentB/>
}
// what is different if I write like this
function App(isTrue){
return(<>
{isTrue && <Component/>}
{!isTrue && <ComopnentB/>}
</>
)
}
2
Answers
There is no difference, in either case the same jsx – ComponentA will render.
The reasoning:
a) isTrue is a truthy value in either case
b) The logical && expression, isTrue && Component A, will evaluate true and return the right-side value which is the component Component A.
c) !isTrue && Component A, will evaluate to a false value, which React will ignore from rendering.
d) Fragment tag <></> does not have any trace in the resultant HTML
In your case – with different components – there’s no noticable difference, since distinct components do not share state. The returned React elements (i.e. component subtree) from the functions is slightly different, but the rendered HTML will be identical.
If you desugar the JSX, your components’ implementation (assuming that
Component
andComopnentB
in the original question are typos; assuming that the function signature is actuallyApp({isTrue})
to match the required signature of React function components) is actually:And inlining those
createElement
calls:As you can see, the component tree is vastly different:
false
Things become more interesting if you introduce state into your ComponentA and render it twice. After all, the question is tagged react-state-management.
If you click the checkbox to toggle the
isTrue
prop of your nested components, you will notice that the state ofComponentA
insideAppShortCircuit
will be reset, but the state of the component insideAppIf
is retained. This is because state is tied to a position in the render tree.AppIf
is effectively rendering the same tree, regardless of the prop’s value. Both components are rendered in the same position, so they share state.AppShortCircuit
is either rendering[false, ComponentA]
or[ComponentA, false]
. The components do not share the same position in the tree and consequently do not share state.