How do you handle dialog's content state lifecycle? Do you scope your dialog content?
Whenever it's time to implement a Dialog, this thing always bugs me out, whether to scope the Dialog content state or keep everything in one component.
A typical dialog examples look something like this:
function EditProfileDialog () {
// ... your states
return (
<Dialog>
<DialogTrigger>Open</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Profile</DialogTitle>
</DialogHeader>
<form>
// ...form fields
</form>
</DialogContent>
</Dialog>
)
}
In this context the dialog's content is the form.
The issue with this pattern is, the form state always stays mounted, regardless of whether the dialog is open or not. If you want to reset the form state when the dialog closes, you have to manually hook into onOpenChange and reset things yourself. Another case is if you want to run logic when the dialog opens or closes, you end up syncing everything manually with the dialog’s open state. You lose all the benifit of React's lifecycle.
In my opinion, it makes more sense to scope the dialog's content in seperate component, so it only initializes when the dialog opens. That way, closing the dialog naturally resets everything without extra boilerplate.
function EditProfileDialog () {
return (
<Dialog>
<DialogTrigger>Open</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Profile</DialogTitle>
</DialogHeader>
<Form />
</DialogContent>
</Dialog>
)
}
function Form() {
// ...your states
return (
<form>
// ...form fields
</form>
)
}
How do you guys usually approach this pattern?