One more approach you might consider adding to your list is the “guard clause”:
constMyComponent=({name})=>{if(!name){// 👈returnnull;// 👈 guard clause}// 👈return<p>Hi! My name is {name}.</p>;};exportdefaultMyComponent;
This conditional rendering tactic will prevent the entire component from rendering (including any unnecessary <div>s) if your conditions are not met.
Abstracting the logic from your return() statements in this way also helps by avoiding confusing nested conditionals, improving the readability of your code.
Thank you for writing about Guard Clause in details. I didn't know about this. I have modified the article and added this example under Logical Operator section as Guard Clause has ! (NOT Logical Operator).
Cheers, mate. But just to be clear, a guard clause doesn’t specifically use a NOT operator. It can be any sort of expression that, when evaluated to be false (or falsy, depending on your logic), returns the function early.
If I remember correctly, return on its own infers a return type of void, whereas return null is an acceptable React.ReactNode return type, as far as TypeScript is concerned.
And void in turn results in undefined on the caller, which React now supports, but I would still discourage. The reason support for it was added was, in part, inconsistency between nested and root-level conditional rendering.
One more approach you might consider adding to your list is the “guard clause”:
This conditional rendering tactic will prevent the entire component from rendering (including any unnecessary
<div>
s) if your conditions are not met.Abstracting the logic from your
return()
statements in this way also helps by avoiding confusing nested conditionals, improving the readability of your code.It's not rendering
<div>
s it's using Fragments.Correct—I meant that more broadly regarding returning
null
, not pointing to any specific examples.Thank you for writing about
Guard Clause
in details. I didn't know about this. I have modified the article and added this example under Logical Operator section asGuard Clause
has!
(NOT Logical Operator).Cheers, mate. But just to be clear, a guard clause doesn’t specifically use a NOT operator. It can be any sort of expression that, when evaluated to be false (or falsy, depending on your logic), returns the function early.
Very useful information, thank you. 😃
Why not just
return
instead ofreturn null
?If I remember correctly,
return
on its own infers a return type ofvoid
, whereasreturn null
is an acceptableReact.ReactNode
return type, as far as TypeScript is concerned.And void in turn results in undefined on the caller, which React now supports, but I would still discourage. The reason support for it was added was, in part, inconsistency between nested and root-level conditional rendering.
Yes, you can definitely do that as we know whenever JavaScript sees the
return
keyword, it immediately exits the function.