Ever needed to wire up a confirmation dialog in React? You know the ones: “Really delete this file? — Yes / Cancel”
These dialogs tend to follow a consistent pattern:
- User tries to do dangerous/destructive action
- Modal pops up asking if they’re really really sure
- On Cancel: hide the modal, do nothing
- On Confirm: do the action, and then hide the modal after the action is done
I worked on an app that had a need to protect dangerous actions like Delete, in a few places across the app.
The asynchronous nature of the flow (Confirm, wait until done, then close) meant that there would be plenty of finicky
useEffect code to show and hide the modal, wait for the async API call to finish before hiding it, and so on.
Or… could I avoid
useEffect entirely by using a state machine?
It turned out the answer was yes!
In this article we’ll build a reusable state machine using React and Robot to handle this modal confirmation flow, and wrap it up into a custom hook.