Conditional rendering, two ways, which one is better for website performance?

Viewed 41

I read a comment (posted below) from this article and it made me think about this scenario.

Out of case 1 and case 2, which one would lead to better, faster website performance?

Scenario

  1. we created a card component

  2. we expect this card component to have text in order to be displayed

  3. (case 1) should we check if the text is available every time we use the component

  4. (case 2) or would it be better to only perform the check in the Card component


CASE 1

IndexPage.js

import Card from './Card'

const paragraph = 'good morning world';

export default function IndexPage(props) {
    return (
        <>
            /* perform check outside component */
            /* card component never runs if no text provided */
            { paragraph && <Card paragraph={paragraph}></Card> }            
        </>
    )
}

Card.jsx

export function Card(props) {
    return (
        <div className="card">            
            <p>{props.paragraph}</p>
        </div>
    )
}

CASE 2

IndexPage.js

import Card from './Card'

const paragraph = 'good morning world';

export default function IndexPage(props) {
    return (
        <>
            <Card paragraph={paragraph}></Card>             
        </>
    )
}

Card.jsx

export function Card(props) {
    return (
        /* card component was ran once to perform the check below */
        props.paragraph &&
            <div className="card">            
                <p>{props.paragraph}</p>
            </div>            
    )
}

https://blog.logrocket.com/react-conditional-rendering-9-methods/

1 Answers

Case 1 will have a better performance. But is this really the case? They will have difference like few milliseconds. React is something that does not care about performance. Case 1 is like a code smell, if you skip to check, it may cause problems

Related