How to conditionally render React components using React hooks

Last updated on Aug 29, 2020 by Suraj Sharma



In this tutorial, you will learn 3 ways to conditionally render React components in React JS using React hooks.

There are use cases in web development when we render an element if the first condition is met and render another element when the second condition is met.

JSX supports simple conditional statements of javascript like if-else statement, and switch statement.

We will apply the same knowledge of conditional statements in Javascript to conditionally render React components in jsx.

Here are 3 ways of conditionally rendering components in React.



Getting Started


Let’s create two simple components Loader and List

Loader component will render a loading message when data is being fetched.

List component will render the fetched data.


// Loader.jsx

import React from 'react';

const Loading = () => {
  return (
   <p>Loading...</p>
  )
}

export default Loading;


// List.jsx

import React from 'react';


const List = ({ items }) => {
  return (
    <ul>
      {items.map(item=>(
        <li>{item}</li>
      ))}
    </ul>
  )
}

export default List;

Now define two local states; isLoading and data inside the App component using useState() hooks.

isLoading is a boolean value, which we have initialised to true, Inside the useEffect we are setting it to false using setTimeout.


// App.jsx

import React from 'react';
import List from './components/List';
import Loader from './components/Loader';

const App = () => {
  const [data, setData] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  React.useEffect(()=>{
    setTimeout(()=>{
      setData(["Apple", "Orange", "PineApple"]);
      setIsLoading(false);
    }, [2000]);
  })

  return null;
}

export default App;


1. If-else Statement


At the initial render of the App component isLoading is true, therefore the Loader component is rendered, after 2 seconds is elapsed, the Loader component is removed(unmounted) and the List component gets rendered.

This is a trivial example of conditionally rendering React components using React hooks.


if (!isLoading) {
  return <List items={data} />
}
return <Loading />

Conditional rendering using if-else statement




2. Ternary Operator (a?b:c)


Using Ternary opertor in React is similar to how we use it in Javascript. Hence, the above return statement looks like this


return isLoading ?  <Loader /> : <List items={data} /> ;


3. Logical AND && Operator


In Javascript,

const a = ‘value’;
let val = true && ‘value’ // === ‘value’

val = false && ‘value // === false;

We are going to use the above logic to render the List component, when data.length is 0 nothing gets rendered, after 2 seconds data.length equals 3 and !!data.length === true which renders the List component.


return <div>{!!data.length && <List items={data} />}</div>;


Conclusion


In this tutorial, you have learnt 3 ways to conditionally render components in React.

Conditionally adding and removing larger DOM components will force React to render larger DOM elements, which might affect your React app performance.

Always look for how you can minimize DOM manipulation when using conditional rendering in React. One way would be to render or unmount only a small portion of DOM elements.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.