Great question. This a React gotcha, more than a performance problem. The React docs, in my opinion, just dont make this clear enough, and Ross Allen's answer is right on and hints at that, but let me try to clarify even more.
If you have any doubt that your conditional could evaluate to a falsy value—such as array.length
(and thus react will render an array length of zero) or the string rendered could be an empty string—use the ternary!
Otherwise you can use the &&
operator freely and confidently. An example would be something like
count && count > 3 && (
<div>In stock</div>
)
The above check will either be true or false. So you're safe. Note that we ALSO checked to make sure count
is truthy first and then we checked the conditional we're looking for specifically. That way we eliminate the possibly of a falsy value being rendered unintentionally.
Another example:
data?.order_type && data.order_type === 'patient' && (
<div>For patients</div>
)
This will also only be true or false. Note I also included the ?
as an optional chain. This is shorthand in JavaScript that allows you condense some of your truthy checks. data?.order_type
checks that data
is truthy first, and if it is, the evaluation continues, otherwise it will exit the evaluation.
When to use the ternary:
If your conditional could evaluate to a falsy value. For example:
items.length ? ( // length could be 0
<div>available</div>
: null
)
However if you change the above to items.length > 0
, then you're good to with &&
operator.
items.length > 0 && ( // length could not be 0
<div>available</div>
)
When in doubt, make your checks more specific and be sure you're thinking falsy/truthy when you're dealing with conditional rendering. It is a gotcha, but once you get the idea behind it, it all makes more sense.