Dony Joseph
Dony Joseph

Reputation: 629

react render Logical && vs Ternary operator

In the react render() when the value of x equals 1 both the logical && and ternary operator will display Hello and both are syntactically correct. I always used the && when I don't want to show the else part of my condition, but I have come across one code base where most of the places they used ternary operator with null instead of &&. Is there any performance gain or any other advantage of using one method over the other?

return (
    <div>
        <div>{x === 1 && <div>Hello</div>}</div>
        <div>{x === 1 ? <div>Hello</div> : null}</div>
    </div>
);

Upvotes: 32

Views: 32756

Answers (6)

Andr&#233;s Manco
Andr&#233;s Manco

Reputation: 131

There is no performance advantage. So its up to the developer to know the different rules and exceptions that could happen.

To make it simple my rule would be: Use ternary operator for every case BUT when I am sure my variable is always a boolean

 const [shouldDoSomething, setShouldDoSomething] = useState(false)

Here my state will always be boolean if I just toggle it Then:

<>

    {shouldDoSomething && <Something/>}

<>

For any other case ternary will do it.

Upvotes: 0

chety
chety

Reputation: 156

It is advised to use ternary operator instead of logical &&, ||. There is a major difference if you do not take it into account. You can read the details in the below article.

Kent Blog About this

Upvotes: 3

Cat Perry
Cat Perry

Reputation: 1042

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.

Upvotes: 7

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14208

Is there any performance gain

The answer is NO.

In React Js, It's called [Inline If with Logical && Operator]

It works because, in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after "&&" will appear in the output. If it is false, React will ignore and skip it.

Upvotes: 9

Ross Allen
Ross Allen

Reputation: 44880

There's no significant performance difference, but because 0 and empty string "" are "falsy" in JavaScript I always opt for the ternary operator so the next person to edit my code knows my exact intention.

Example:

const count: number | null = 0;
const firstName: number | null = "";

return (
    <div>
        {/* Was this a bug or is `0` really not supposed to render??
          * This will just render "0". */}
        <div>{count && <>The count is {count}</>}</div>

        {/* Okay got it, there's a difference between `null` and `number` */}
        <div>
          {count == null ? <>No count at all</> : <>Count of {count}</>}
        </div>

        {/* Was this a bug too or is `""` supposed to render nothing?
          * This will just render an empty string. */}
        <div>{firstName && <>My name is {firstName}</>}</div>

        {/* Okay now I see `null` / `undefined` vs. a string */}
        <div>
          {firstName == null ? <>No name</> : <>This *will* render {firstName}</>}
        </div>
    </div>
);

Upvotes: 31

vipcxj
vipcxj

Reputation: 1038

No performance gain, just easy to format.

    <div>
        <div>
            {x === 1 ? (
               <div>Hello</div>
            ): null}
        </div>
    </div>

And if you want to deal with else part later, modify little

    <div>
        <div>
            {x === 1 ? (
               <div>Hello</div>
            ): (
               <div>just change here.</div>
            )}
        </div>
    </div>

Upvotes: 3

Related Questions