DEV Community

Jokerwolf
Jokerwolf

Posted on

⚛️ React conditional rendering

A question popped up in my head during a PR review: is it OK to put a rendering condition into the render function (return statement for a functional component) instead of a component reference assignment?

Imagine having this 'heavy' calculation React-component.

React TypeScript Code of the Heavy component

It generates a list of elements based on the count prop and logs into a console for illustrative purposes.

Let's say we instantiate it like this.
React TypeScript Code of the App component. Rendering condition in return statement
We have the heavy reference and log it into a console for illustrative purposes.

Won't this way of instantiating actually run some of those 'heavy' calculations inside the Heavy component at the moment we create the heavy reference? What would be the console log if we run this code when shouldRenderHeavyComponent returns false?

I was a bit surprised to only see the heavy reference being logged. Was expecting to see at least the constructor logging something.
DevTools Console with logs

So no 'heavy' calculations happening and this approach looks nice. We can assign a component once and if we'll have a longer code for App component, we'll be able to see in the return statement why exactly heavy should/shouldn't be rendered.
The drawback I see is having an actual reference hanging around.
Imagine somebody doing a check somewhere later in code:
React TypeScript Code of the App component. Rendering condition in return statement. If-statement added

Now heavy reference is an actual object, so some code will run.

And of course we have some memory allocated for the object, which doesn't seem like a big thing, but still bothers me a bit as in the end it was all for not actually rendering heavy.

That's why although the idea of a rendering condition being close to the actual rendering is compelling, I would stick to moving it into the assignment.
React TypeScript Code of the App component. Rendering condition in assignment

Console would still have only heavy logged, but now it'll be null as expected.
DevTools Console with logs

To answer my initial question: it looks OK-ish to put a rendering condition into the render function (return statement for a functional component) instead of a component reference assignment, but not having a potentially obsolete reference hanging around feels nicer to me personally.

Wonder what else I might be missing? 🤔

Discussion (2)

Collapse
emanuel_hodl profile image
Emanuel

TLDR => It's okay!

Thanks for the article! Nice Work!

Collapse
jokerwolf profile image
Jokerwolf Author

Perfect summary 👌