How to Handle Modals In A Large-Scale React App — Render Manager
Modals, Dialogs, Notifications, and Snackbars, are all examples of “global components” — as I call them. These are components that should be displayed at an app level and should be triggered from anywhere.
I work with large-scale applications which show a lot of Modals and notifications and sometimes, we even need to component them on the fly and not have a specific component for them.
The Problem
Let's look at this typical example of how developers normally render Modals:
function App() {
const [editModalVisible, setEditModalVisble] = useState(false);
const displayEditModal = () => {
setEditModalVisble(true)
}
const hideEditModal = () => {
setEditModalVisble(false)
}
const handleSave = () => {
// some logic to save data
hideEditModal()
}
...
return (
<div className="App">
<Button onClick={displayEditModal}>Edit Name</Button>
...
<EditNameModal
visible={editModalVisible}
name={name}
onSave={handleSave}
onCancel={hideEditModal}
/>
</div>
);
}
This is an example of a single modal rendered inside the component which needs it. As you can see, there are a lot of simple functions dedicated to this modal.