What is the best practice for checking if the value exists before using it in a component

Viewed 96

I have a custom hook that fetches data and then I want to display that data.

But it isn't available at render so I've been doing this

<li>{data && data.name}</li>

Is there a better way?

3 Answers

I would do something like this

{data.name && 
  <li>{data.name}</li>
}

This way the tag is only rendered if the exact value exists otherwise no element will be rendered.

the best way and much more optimized way is

<li>{data?.name}</li>

You can do:

{data && <li>data.name</li>}
Related