Home > Enterprise >  React Best Practices: Where to *not* render a component?
React Best Practices: Where to *not* render a component?

Time:04-04

I came across some code in review and had a question on best practices. Here's the scenario:

I've got a Hyperlink component with a url prop. If for some reason url is falsy, Hyperlink renders null.

simplified example:

const Hyperlink = ({ url }) => {
  return !url ? null : <SomethingElse url={url} />;
};

Does this logic belong in the Hyperlink component, or should it be the responsibility of the parent component to determine whether or not to render something?

example:

const MyParentComponent = ({ url }) => {
  return !url ? null : <Hyperlink url={url} />
};

This keeps Hyperlink dumb, with the downside of having to sprinkle that logic in places url is optional.

CodePudding user response:

If the conditional rendering is :

condition ? something : null

I prefere using:

condition && something

Since conditional rendering should be used for cases like:

condition ? something : somethingElse

Back to your question, if the Component has some heavy calculations before the return, it's common sense that you are wasting resources performing them since it won't return nothing if condition is false, so it' s better to use:

condition && <Component/> 

But in most cases, especially if you have stateless components with no logic like that one, you won't experience particular differences between the two approaches, basically by doing the conditional rendering inside the component, you are just wasting a React.createElement().

I personally use

condition && <Component/>

in cases like that, if it's possible, since I find to be very semantically uncorrect for a Component to possibly render nothing. If you call your Component HyperLink, I expect it to return something, possibly a link. There are cases where you are forced to return nothing, and it's okay, but I try to avoid it.

CodePudding user response:

Usually these type of checking should be done using Typescript. Answering to your question it should depend upon your project scenario.

If you feel the url the Hyperlink component will receive can be null or undefined you can put the check in the Hyperlink component.

But if you think only in MyParentComponent the case will occur where url will be null you can think of conditionally rendering the component.

  • Related