Friday, March 6, 2026

&&

 Avoid unsafe "&&" Operator for Conditional Rendering in React and Next.js

Basically the TLDR is:
isVisible && <item />
to control visibility in React isn't great... edges cases of falsiness (like "NaN") may show up when you were hoping for a blank. So use the ternary operator with "null" as the false case instead.

On my team I pushed it a little further and asked if we could prefer 

isVisible ? <item /> : null;

over

isHidden ? null : <item />

admittedly the case the triggered me was like

isReadOnly || !featureFlagForItem ? null : <item />

which is kind of a tangle to read.


No comments:

Post a Comment