Member-only story
Stop Using “&&” for Conditional Rendering in React Without Thinking
Avoid bugs by using `&&` correctly in React components
If you’ve seen any React application, you know how to conditionally render parts of a component depending on props and state. Although there are multiple ways of conditional rendering, this article focuses on the JavaScript &&
operator. The main reason for this emphasis is that the&&
operator often leads to UI bugs, which can be easily avoided and it’s often not mentioned.
Content
· How “&&” Works
· Why Not To Use “&&”
· What To Use Instead Of “&&”
· Best React Books and Courses in 2023
How “&&” Works
A classic example of its use in React would be:
function MyComponent({ condition }) {
return (
<div>
<h1>Title</h1>
{condition && <ConditionalComponent />}
</div>
);
}
Briefly summarized:
- if
condition
is a truthy value,<ConditionalComponent />
is rendered - if
condition
is a falsy value,<ConditionalComponent />
is not rendered