For a component that is hidden at some point in its lifecycle, what is the best way to render it? 1) render the component, but do not show it (display:none). 2) render the component only when needed. What is better for performance? If the component's props and state update later, would it be better to have the component present, but hidden in the virtual DOM?
render() {
return (
<div style={{display: this.props.visible ? 'block' : 'none'}}>
<RestofComponentHere />
</div>
);
}
or this:
render() {
if (!this.props.visible) {
return null;
}
return (
<div>
<RestofComponentHere />
</div>
);
}
Just go with what works best for that situation. Sometimes it's method 1 and sometimes method 2. If you find out that it's slowing down your app then it's pretty easy to convert to method 1, but this should only if happen if you are conditionally rendering a ton of times. When you have a ref to the component then you want to always render it so that you can access the ref in
componentDidMount
and so you would have it hidden.First method is faster as shown in answer here but don't do micro optimizations for the sake of it if conditionally rendering is cleaner code.
I'v used a mixture in my apps.