Single-Open Async Tooltip Panels with Keyboard Support in React
Data Structure DesignModel answerLast updated
Design a React popover that fetches data when opened, stays exclusive across many triggers, ignores stale responses, and handles focus, Esc, and outside clicks accessibly.
Build a Fetch-on-Open Popover
Your page has several buttons. Each one opens a small floating panel that loads its own data when the panel opens. Implement a reusable React component with this signature:
function Popover({ triggerId, fetchData }) {
// triggerId: unique string identifying this popover and its button
// fetchData: function that returns a Promise with the content to show
}
What it must do
- Accessibility. Use suitable ARIA attributes (for example
aria-expanded,aria-describedby,aria-busy). Keyboard focus must be handled sensibly when the panel opens, either trapped inside it or moved in a deliberate way. - Loading and result states. Show a loading indicator while the request is pending, then render the data on success.
- Stale-response protection. If the user opens one popover, quickly opens another, then returns to the first, the first must display the result of its most recent request. A slow earlier response must never overwrite it.
- Exclusive opening. Only one popover may be open at any moment, even though many triggers exist.
- Anchored placement. The panel appears next to the button that opened it. Simple absolute positioning is fine, or explain how you would use a positioning library such as Floating UI.
- Dismissal. Pressing
Escor clicking outside the panel closes it. - Failures. If
fetchDatarejects (or throws), handle it gracefully.
Behavior examples
- Clicking "Load User A" shows a panel at the button's position with a spinner, which is replaced by the user profile once data arrives.
- Pressing
Tabreaches the button andEnteropens the panel. PressingEsccloses it and focus returns to the button.
What to deliver
Write the component (plus any helper hook or context you need) and explain your key decisions: where shared state lives, how you discard stale results, how focus is handled, and which edge cases you considered. State any assumptions, such as whether the component renders its own trigger button.
Hints
Hint 1
Which piece of state must be shared among all popovers to guarantee only one is open? Consider a single `openId` in a context, with each popover open when it equals its own `triggerId`.
Hint 2
Tag each request with an incrementing counter (and optionally an AbortController). Only commit a response if its tag still equals the latest counter value; bump the counter on close and unmount.
Hint 3
Think about the closing paths separately: Esc should return focus to the trigger, while an outside click should not steal focus. Make the outside-click handler ignore clicks on the trigger itself to avoid a close-then-reopen double toggle.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into four independent concerns.
1. Exclusivity through shared state
Wrap the page in a PopoverProvider that stores a single openId (string or null). Every Popover computes open = openId === triggerId. Because only one value exists, two popovers cannot be open simultaneously, and no instance needs to know about the others.
Closing uses a functional update: setOpenId(cur => cur === triggerId ? null : cur). This prevents a late close request from popover A from accidentally closing popover B, which may have opened in the meantime.
2. Latest-request-wins fetching
Put the fetch lifecycle in a hook, for example useLatestRequest(fetchData), which holds:
reqIdRef, an incrementing counterctrlRef, the currentAbortControllerstate:{ status: "idle" | "loading" | "success" | "error", data, error }
run() first cancels any previous request (abort, then increment the counter), captures the new ID, sets status to loading, and calls fetchData({ signal }). When the promise settles, the result is committed only if id === reqIdRef.current.
Trace the tricky scenario: open A (request 1), open B (A closes, which aborts and bumps the counter), open A again (request 2 gets a new ID). If request 1 resolves late, its ID no longer matches, so it is silently dropped. Correctness depends on the ID check and not on fetchData honoring the abort signal; aborting is just an optimization that saves network work.
Wrap the call as Promise.resolve().then(() => fetchData(...)) so synchronous throws become rejections and flow through the same error path. Ignore AbortError. Real failures set status: "error" and render a message with a Retry button. Clean up on unmount by calling cancel, so setState never fires on an unmounted component.
3. Rendering and positioning
Render the panel into document.body with a portal so ancestor overflow: hidden or stacking contexts cannot clip it. Compute coordinates from trigger.getBoundingClientRect() in a layout effect:
- Default placement is below the trigger with an 8px gap.
- If the panel would overflow the viewport bottom, flip above.
- Clamp
leftto stay within[gap, innerWidth - width - gap]. - Add
scrollX/scrollYwhen using absolute positioning on the body. - Recompute on
resize, onscroll(capture phase, so nested scroll containers count), and via aResizeObserveron the panel, since its height changes when content replaces the spinner.
In production, Floating UI (useFloating with flip, shift, offset, autoUpdate) provides all of this and is better tested.
4. Accessibility and focus
- Trigger:
aria-expanded={open},aria-controls={popoverId},aria-haspopup="dialog". - Panel:
id={popoverId},role="dialog",aria-busy={status === "loading"}, and a label or description reference (aria-describedby) pointing to the content region. Usearia-live="polite"for the status text so screen readers announce loading and results. - On open, move focus into the panel (give it
tabIndex={-1}and focus it, or focus the first focusable element). TabandShift+Tabcycle within the panel while open (query focusable elements and wrap at the ends).Esccloses and restores focus to the trigger.- Outside click closes without moving focus, since the user has chosen a new target.
Register the document-level keydown and pointerdown listeners only while the popover is open, so there are O(1) global listeners no matter how many triggers exist. The outside-click handler must ignore clicks inside the panel and on the trigger; otherwise the document handler closes the panel and the button's onClick immediately reopens it.
Sketch
const Ctx = createContext(null);
export function PopoverProvider({ children }) {
const [openId, setOpenId] = useState(null);
return <Ctx.Provider value={{ openId, setOpenId }}>{children}</Ctx.Provider>;
}
function useLatestRequest(fetchData) {
const [state, setState] = useState({ status: "idle", data: null, error: null });
const reqId = useRef(0);
const ctrl = useRef(null);
const cancel = useCallback(() => {
ctrl.current?.abort();
ctrl.current = null;
reqId.current += 1;
}, []);
const run = useCallback(() => {
cancel();
const c = new AbortController();
ctrl.current = c;
const id = reqId.current;
setState({ status: "loading", data: null, error: null });
Promise.resolve()
.then(() => fetchData({ signal: c.signal }))
.then(
data => { if (id === reqId.current) setState({ status: "success", data, error: null }); },
error => {
if (id !== reqId.current || error?.name === "AbortError") return;
setState({ status: "error", data: null, error });
}
);
}, [fetchData, cancel]);
useEffect(() => cancel, [cancel]);
return [state, run, cancel];
}
In Popover, an effect on open calls run() when opening and cancel() when closing. Another effect focuses the panel on open. A third registers the Escape, Tab, and outside-click handlers while open.
Complexity
- Open, close, and commit are O(1).
- Each
Tabpress costs O(F) to query F focusable elements. - Each scroll or resize reposition is O(1).
- Space is O(1) per instance.
Trade-offs
- Context versus a global store. Context is enough here because only one value changes; a store would only be needed at larger scale.
- Cache versus refetch. Refetching on every open guarantees freshness but costs latency. A cache with stale-while-revalidate (React Query, SWR) is a natural follow-up.
- Focus trap versus non-modal popover. A true modal traps focus and inerts the background. A non-modal popover can let focus leave, closing on blur. Pick one deliberately and state it.
Edge cases
fetchDatathrows synchronously, rejects, or never resolves: the spinner persists, but Esc and outside click still work.- Unmount during a request: cleanup aborts and invalidates the ID.
- Panel near the viewport bottom: flip above.
- Same trigger clicked twice: toggles closed.
- Trigger removed from the DOM while open: guard focus restoration with
isConnected.
Common mistakes
- Using a boolean "is latest" flag per effect run instead of a monotonic ID, which fails when the same popover reopens.
- Relying on
AbortControlleralone; manyfetchDataimplementations ignore the signal. - Forgetting to exclude the trigger from the outside-click check, causing flicker or double toggles.
- Stealing focus on outside click.
- Positioning once at open time and never updating when content size or scroll changes.
- Leaving global listeners attached for every closed popover.