2 minutes read

Rendering React components is very important since it can make your app behave faster or slower, depending on your approach for rendering components, re-rendering components based on condition or state/props change.

Here are a few methods you can use to render React components:

If Else conditional operator


import React from 'react';
import ReactDOM from 'react-dom';

function GuestComponent() {
    return 

Welcome guest

} function BlogComponent() { return

Welcome back

} function MyComponent(props) { const isSubscribed = props.isSubscribed; if(isSubscribed) { return ; } return } export default MyComponent; ReactDOM.render( , document.getElementById('root'))

Ternary operation in React

Conditionally rendering React elements inline means to use the JavaScript conditional operator:

condition ? expr1 : expr2


import React from 'react';
import ReactDOM from 'react-dom';

function GuestComponent() {
    return 

Welcome guest

} function BlogComponent() { return

Welcome back

} function MyComponent(props) { const isSubscribed = props.isSubscribed; return ( <> { isSubscribed? : } ) } export default MyComponent; ReactDOM.render( , document.getElementById('root'))

Inline If with Logical && Operator

In JS
true && expression
always evaluates to expression, so it will render, accordingly
false && expression
always evaluates to false, so React will ignore and skip it.

import React from 'react';
import ReactDOM from 'react-dom';


function MyComponent() {
    const errors = ['error1', 'error2'];

    return (
        <>
            { errors.length > 0 &&
                

You have {errors.length} errors.

} ) } export default MyComponent; ReactDOM.render( , document.getElementById('root'))

Inline If-Else with Conditional Operator


import React from 'react';
import ReactDOM from 'react-dom';


function MyComponent() {
    const isLoggedIn = false;

    return (
        
The user is {isLoggedIn ? 'currently' : 'not'} logged in.
); } export default MyComponent; ReactDOM.render( , document.getElementById('root'))

Return null to Prevent Component from Rendering

Returning null from a component’s render method does not affect the firing of the component’s lifecycle methods.


import React from 'react';
import ReactDOM from 'react-dom';


/**
 * @return {null}
 */
function MyComponent(props) {
    if (!props.warning) {
        return null;
    }

    return (
        
Warning!
); } export default MyComponent; ReactDOM.render( , document.getElementById('root'))

Immediately-invoked function expressions

Functions that are executed immediately after they are defined:



( function (/* arguments */) {
    // ...
} ) (/* arguments */);

Or with arrow functions:


( (/* arguments */) => {
    // ...
} ) (/* arguments */);

How Much Traffic Can Your Website Handle?