0 day streak
javascript / expert
Snippet

Mastering Event Capture Phase for Global Interception

React supports the capture phase through 'Capture' suffixes (e.g., onClickCapture). Intercepting events during the capture phase (top-down) rather than the bubbling phase (bottom-up) is essential for building complex UI components like modals or analytics wrappers that need to intercept interactions before child elements process them.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function GlobalClickTracker() {
const containerRef = useRef(null);
useEffect(() => {
const handleCapture = (e) => {
console.log('Intercepted in capture phase:', e.target);
// Can prevent events before they reach children
// e.stopPropagation();
};
const el = containerRef.current;
el.addEventListener('click', handleCapture, true);
return () => el.removeEventListener('click', handleCapture, true);
}, []);
return <div ref={containerRef} onClickCapture={() => {}}>...</div>;
}
react
Breakdown
1
addEventListener(..., true)
The third argument 'true' enables the capture phase instead of the default bubbling phase.
2
onClickCapture
React's synthetic event prop equivalent for the DOM capture phase.
3
e.stopPropagation()
In the capture phase, this prevents the event from reaching any child elements.