The common example of modal usually goes like this:
import * as React from 'react';
import { Modal, Portal, Text, Button, Provider } from 'react-native-paper';
const MyComponent = () => {
const [visible, setVisible] = React.useState(false);
const showModal = () => setVisible(true);
const hideModal = () => setVisible(false);
const containerStyle = {backgroundColor: 'white', padding: 20};
return (
<Provider>
<Portal>
<Modal visible={visible} onDismiss={hideModal} contentContainerStyle={containerStyle}>
<Text>Example Modal. Click outside this area to dismiss.</Text>
</Modal>
</Portal>
<Button style={{marginTop: 30}} onPress={showModal}>
Show
</Button>
</Provider>
);
};
export default MyComponent;
My question is. Why is this the recommended usage instead of just unmounting the component when is not needed anymore? Something like this:
visible && (<Modal visible={true} onDismiss={hideModal} contentContainerStyle={containerStyle}>
<Text>Example Modal. Click outside this area to dismiss.</Text>
</Modal>)
Is there any pro or cons of doing it one way or another? Is there a particular or good reason I have to do it in the first("official") way?
Let me borrow this answer by jimfb to the same question on github repo of react:
Hiding via CSS is slightly faster, but it has the downside that it means your dom/react tree is bigger, which means your reconciliations are bigger (slower) and your app is using more memory - even when the tree is not visible. If you can't tell the difference between the two, in terms of performance, we would recommend unmounting (since then you're cleaning up your memory and keeping your tree small).