Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
useClickOutside
medium20 min
Call a callback when a document click occurs outside the element currently stored in a React ref.
Requirements
Implement useClickOutside(ref, callback). ref.current is an Element or null. Subscribe to bubbling document click events and return undefined.
Invoke callback once with the original MouseEvent when the clicked Node is outside ref.current. Clicking the referenced element itself, its nested descendants, or a text-node descendant must not invoke it.
If ref.current is null, ignore the click. Read the current element at event time so replacing or clearing ref.current changes behavior without a rerender. Ignore non-Node event targets.
After rerender, use the latest callback and ref object. Remove obsolete listeners and clean up on unmount. Each instance owns its listener, and Strict Mode replay must leave only one active listener.
Clicks stopped before reaching document are not observed. Shadow DOM/portal-specific policies and pointer-down detection are outside scope. Use DOM fixtures from the tests; no HTML or CSS implementation is required.
Examples
Example 1
Input: useClickOutside(panelRef, () => setOpen(false));
Output: Clicks outside the panel close it; clicks inside do not.
A document-click subscription scoped to the current ref element.