When to use the open prop vs. conditionally rendering a Material-UI Modal component?

Viewed 160

When using Material-UI's Modal component (or any of the components built using it), is there any benefit in using the open prop vs. conditionally rending the component? I've noticed that you lose the nice closing transition, but is there any performance benefit if there are a lot of Modals?

Example using the open prop:

    const [openModal, setOpenModal] = React.useState(false);

    return (
        /* code to set openModal to true */
        <Modal open={openModal} onClose={() => setOpenModal(false)}>modal stuff here...</Modal>
    );

Example using conditional rendering:

    const [openModal, setOpenModal] = React.useState(false);

    return (
        /* code to set openModal to true */
        {
            openModal &&
                <Modal open onClose={() => setOpenModal(false)}>modal stuff here...</Modal>
        }
    );
1 Answers

I think the second approach could be less performant if you look the Modal component source code you can see a lot of initialization going on in the code, useEffects and some other stuff that every-time you conditionally render the Modal, it will be mounted again in the DOM, while if you keep the open state controlled by the modal itself, the component will not be mounted again, at least not the initialization and it will be more efficient IMO. I suggest to you to read the source but for me always re render something and mounting it would be less efficient.

Related