I have a parent component with reactive vars that are populated with data from a Mongo collection. The child modal dialog modifies this information, causing a re-render of the parent component — and also the modal dialog.
Obviously the modal dialog shouldn't be re-rendered. I tried lifting the open/close state to the parent, but the re-renders still occur.
What are ways that I can prevent this from happening?
Thanks in advance!
I tried lifting the open/close state to the parent, but the re-renders still occur.
Memoization using React.memo or useMemo: Wrap your modal component with React.memo to prevent unnecessary re-renders if its props haven't changed.
const ModalComponent = React.memo(({ isOpen, onClose }) => {
// Your modal content here
});
// In parent component
return (
<div>
{/* Other parent content */}
<ModalComponent isOpen={modalOpen} onClose={toggleModal} />
</div>
);
Alternatively you can use useMemo
const modalComponent = useMemo(() => <ModalComponent isOpen={modalOpen} onClose={toggleModal} />, [modalOpen]);
// In parent component
return (
<div>
{/* Other parent content */}
{modalComponent}
</div>
);