Search code examples
reactjstypescriptperformanceif-statementrendering

Improving render of a component: ? operator or if statement?


I have a component with two "phases", depending on a condition. Something like:

if(example){
  return <div> PHASE TWO </div>
} else {
  return <div> PHASE ONE </div>
}

I was wondering if it's better to create two const referring to the two phases or the previous approach in terms of performance.

const phaseOne = () => {
  <div> PHASE ONE </div>
}

const phaseTwo = () => {
  <div> PHASE TWO </div>
}

return example ? phaseTwo() : phaseOne();

In a first moment, I automatically used the second approach (ChatGPT approved), but my senior told me that was better the first one. I know, the second one is better in readability, but I don't see the performance differences.

? operator or IF statement?


Solution

  • the second one is better in readability

    That's all.
    it is not about ? or if they are the same thing.
    in terms of performance, I will not say that the first is more performant because the difference is negligible, but in the second React have to create the two function on each render.