DEV Community

Discussion on: Stop returning NULL components

Collapse
 
jackmellis profile image
Jack • Edited

While I agree in principle with your point - not rendering a component is preferable to rendering a null component - the reasoning is not to do with performance. React components are super cheap to instantiate, like super super cheap.
The reason you should avoid doing this is because you're not in control of the rendering behaviour of your child component, it means your pages not lay out in the way you expect it to, and it is harder to add more conditionals at the top level.
On the other hand however, there are some very valid reasons to render null. If the logic required to determine the show boolean is really tightly coupled to the rest of the child component's behaviour, it seems silly to have to calculate it twice. Also sometimes you want the child component to be totally encapsulated, sometimes you want to drop a component down and you dont care what it does under the hood, the implementation detail shouldn't be leaked if you can help it.
Finally I think your examples aren't quite right. show ?? <MyChildComponent/> will render the child when show is null, otherwise it will render the value of show...

Collapse
 
ucvdesh profile image
Daniel Silva

Well, you're right with the cheapness of React components but you're missing the re-rendering of every single on of the components. If the parent component have a state that changes a lot, your ChildComponent will re-render too, now let's imagine that we have something like a form component that on every keypress will set a state, that will make you loose performance...the same happen if you have something like a graph that will set a lot of states...

On the second pointer, you can have a null validation on the conditional rendering but not on a render from a component, because you will have a useless lifecycle running, so there's no reason why a return (null) will be valid. Although, I did a little disclosure about sometimes you will have something like a wrapper that will not be showing but may still be needed, but still that wrapper will not return just NULL, at least children to be there...

On the error, yeah thanks! I totally miss that! I just fix it but not because the validation wasn't right but because the validation was returning false not null (also that's no good, but the example was explained it with null)