I have a react component that conditionally renders several child components. Simplified code is just:
render(): {
const component1 = condition ? renderComponent2() : null;
const component2 = renderComponent2();
return (
<div>
{component1}
{component2}
</div>
);
}
The problem is that component2
is getting destroyed and re-rendered whenever the condition
changes. I'm trying to prevent that and keep the original element around. I tried adding a key
to component2
with no luck.
[edit] This is happening even when component1
always exists and I change flag on it to hide it or not with CSS :/
If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.
If the child component is re-rendered without any change in its props then it could be prevented by using hooks. React. memo is the savior, it is a higher-order component that memorize remembers) the result i.e. React will skip rendering of that component and reuse the last rendered result. It checks for prop changes.
Have you tried doing it with shouldComponentUpdate? This is exactly what this function should be used for. Just add it to your component2
and add proper condition inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With