DEV Community

loading...

Short Circuit Evaluation with React

2spacemilk profile image Mark Harless ・2 min read

I've been playing with React for several months now. I love it. Reusable components makes front end developing so much easier and enjoyable. Rendering these components using conditional rendering is something I enjoy coding, and I'm not sure why. It's not hard, it's sometimes not easy but I like it regardless. In this blog post, I'm going to show you how to render a component using the "logical &&" method.

Let's consider this code:

import React, { useState } from 'react'
import Welcome from '../components/Welcome'

function About() {

  const [showWelcome, setShowWelcome] = useState(false)

  return (
    <div>
      {showWelcome ? <Welcome /> : null}
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

The code above is a crude illustration of a homepage. If a user is logged in, we want to greet them by rendering <Welcome />. If the user isn't logged in, we don't want to show anything.

So, in between the divs we have a ternary operator. A ternary operator is basically a shorthand for an if... else statement.

if showWelcome is true then render <Welcome /> or else render nothing.

But there's a simpler way to do this using "logical &&". Using the same logic, we can code the following:

{showWelcome && <Welcome />}
Enter fullscreen mode Exit fullscreen mode

Wait a minute 🧐.

At first, it may not make sense. It didn't for me. Let's think about. The && logical operator means that both conditions on either side of it have to be met in order for it to be true. Right now, as the code stands, showWelcome is false because that's what it's initially set at by useState. So nothing, or null, would be rendered. If it were set to true, however, both conditions would be successfully met and then render <Welcome />.

I thought this was a clever way of rendering a component if there wasn't a need for an else statement. If you do need to render one component or another, it's best to use a normal ternary operator as shown in the first code block!

Discussion

pic
Editor guide