'Avoid Rerendering of modal if checkbox is selected
I have modal like below
const Modal = (second) => {
console.log("rendering modal..");
return (
<Modal isOpen={showModal} onClose={() => setShowModal(false)}>
<Modal.Content maxWidth="400px" maxHeight="600px">
<Modal.Body>
<ScrollViewContent />
</Modal.Body>
</Modal.Content>
</Modal>
);
};
And I have checbox inside scrollview like below
const ScrollViewContent = () => {
return (
<ScrollView>
<FormControl mt={4}>
<Checkbox.Group
onChange={setGroupValues}
value={groupValues}
accessibilityLabel="choose values"
>
{projectlist}
</Checkbox.Group>
</FormControl>
</ScrollView>
);
};
I am looping the checkbox list using remote json like below
const projectlist = PjsonList.map((data, key) => {
return (
<Checkbox key={data.pname + data.uid} value={data.uid}>
{data.pname}
</Checkbox>
);
});
My checkbox is appearing and i am able to select , unselect .But evertytime when i check/uncheck i.e when state is updated using setGroupValues , my modal is rendering again creating a blink , how do I avoid the Re-render of the modal , thank you.
Solution 1:[1]
You can convert your modal pure component if you want to prevent re-rendering.
import React, {memo} from 'react';
const Modal = (second) => {
console.log("rendering modal..");
return (
<Modal isOpen={showModal} onClose={() => setShowModal(false)}>
<Modal.Content maxWidth="400px" maxHeight="600px">
<Modal.Body>
<ScrollViewContent />
</Modal.Body>
</Modal.Content>
</Modal>
);
};
export default memo(Modal);
Solution 2:[2]
You can use useMemo() in projectlist. try this:
const projectlist = useMemo(() => PjsonList.map((data, key) => {
return (
<Checkbox key={data.pname + data.uid} value={data.uid}>
{data.pname}
</Checkbox>
);
}), []);
and you can use React.memo for modal component with
React.memo(Modal, (nextProps, nextState) => {
return (
nextState !== `your states`
);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ridvanaltun |
| Solution 2 | Arunabh Verma |
