Is there anyway in React to prevent the Widget
component be unmounted and mounted again when we change the condition
prop?
interface FooProps {
condition:boolean
}
const Foo: React.FC<FooProps> = ({condition}) => {
const widget = <Widget/>
if(condition){
return <ComponentA>{widget}</ComponentA>
}
return (
<ComponentB>
<ComponentC/>
{widget}
</ComponentC>
)
}
2
Answers
For this, you need to do memoization. You will have to use React.memo for this.
Try this and see if its working as per your need. This will render the component only if the props has changed.
It unmounts because the node does not exist in the Virtual DOM anymore. You can not prevent that.
But…
You can make some tricks to make it work
You can hide it via css
Instead of conditionally rendering the component, you can conditionally hide it via
display: none
. It will mount the component twice, but it is not gonna unmount between the rerenders if the condition changesUse common parent
If the element has same parent between the renders it won’t unmount.
<Widget key="widget" />
key is necessary. Since children fromComponentA
compiles into array of react elements, usingkey
prevents unmounting of individual elements if their order change. In the first conditionWidget
is the first element, in the second – the second elementUse Portal
You can attach Widget to the same node of the Virtual DOM and render it wherever you want using
portals
In this example
<Widget />
:content
in theVirtual DOM
content
in thereal DOM
In this example if you click the button it will change the content, but the Widget won’t unmount