Replies: 1 comment
-
I found your blog post today, which brought me here. We have both hit upon the same idea; I wrote a blog post early in 2022 describing an imperative approach to Dialogs (and other components) in React. What I discovered was that when starting out with a purely imperative way to open a dialog and everything seemed splendit at first, that after some time and growing number of use-cases the purely imperative API wasn't enough anymore and I added a declarative way of setting the dialog state. One example started out as:
UI design and requirements were refined over time and changed:
And I believe I stumbled upon one valuable insight there:
Which led me to refine my dialog components: they will now usually offer both ways of interacting with them. I still think an imperative API can make the caller code very clean and I try to accomodate it, but I don't consider it wise to only offer an imperative API without the declarative alternative. However, supporting both approaches does increase complexity considerably inside the dialog implementation. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Take Material UI's
Dialog
component as an example that hasopen: boolean
React prop as a way to manage its open/closed state. In Material UI documentation you will find a usage example similar to this:In the original example, the dialog is used in place. Normally, you want to extract dialog in a standalone component, for example:
Afterwards, the original example could be reduced to the following:
If the dialog can be used without a need to manage its state in-place that code would look nice and clean.
There are multiple ways to implement it, e.g. by introducing a top-level
DialogProvider
component +useDialog(...)
React hook, alternatively you can add an imperative handler to the dialog itself so that it can be opened usingdialogRef.current?.open()
method available on the dialog instance.Now let's see how the implementation of this dialog including
.open()
method implemented withuseImeprativeHandle(ref, ...)
,useState()
React hooks looks like:There are pros and cons of this approach, on the good side is that it's fully self-contained and doesn't rely on any external state management solutions.
Beta Was this translation helpful? Give feedback.
All reactions