Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
useClickAnywhere
easy10 min
Call a React callback for click events that reach the window, and remove the listener when the component unmounts.
Requirements
Implement useClickAnywhere(callback), subscribing to window click events in the bubbling phase. Return undefined.
Pass the original MouseEvent to the current callback exactly once for each event reaching window, including clicks on nested or dynamically created elements.
After rerendering with a different callback, future clicks call the new callback only. Rerendering must not accumulate listeners.
Remove the subscription on unmount. Each mounted hook instance owns its subscription and cleanup. Strict Mode replay must leave exactly one active subscription per instance.
A click stopped before reaching window is not observed. Keyboard-generated clicks are still clicks. No HTML or CSS implementation is required.
Examples
Example 1
Input: useClickAnywhere(event => console.log(event.target));
Output: Logs the clicked target whenever its click reaches window.
Observe window click events with automatic React lifecycle cleanup.