
I thought of a very cheeky analogyโฆ. imagine someone slaps you hard on the cheek, the pain doesnโt just stay there, it spreads across your face and even rings in your ears, and often gives you a headache... Trust me, Iโve received that kind of slap before, from my mom. The sole purpose was to properly reset my brain. ๐ฎโ๐จ
Thatโs event bubbling: the event starts at one element and propagates outward through its parent elements.
When working with events in React, you might have noticed that sometimes multiple event handlers get triggered ๐คทโโ๏ธ, even when you only clicked one element. Well, That&apso;s due to something called event bubbling, a behavior inherited from how the browser handles events.
In the browser, when you click an element, the event doesn&apso;t stop there. It starts from the innermost element and travels up through its parent elements, this is called bubbling.
it is quite similar to ripples in a pond, the disturbance starts at one point and then spreads outward to everything around it.๐ฆ๐
<๐๐๐ซ ๐ค๐ฃ๐พ๐ก๐๐๐ ={() => ๐๐ค๐ฃ๐จ๐ค๐ก๐.๐ก๐ค๐("๐ฟ๐๐ซ ๐๐ก๐๐๐ ๐๐")>
<๐๐ช๐ฉ๐ฉ๐ค๐ฃ ๐ค๐ฃ๐พ๐ก๐๐๐ ={() => ๐๐ค๐ฃ๐จ๐ค๐ก๐.๐ก๐ค๐("๐ฝ๐ช๐ฉ๐ฉ๐ค๐ฃ ๐๐ก๐๐๐ ๐๐")}>๐พ๐ก๐๐๐ ๐ข๐</๐๐ช๐ฉ๐ฉ๐ค๐ฃ>
</๐๐๐ซ>This happens Because the event bubbles up from the button to its parent div, clicking a child element can trigger the parent's event too. ๐งจHow to Stop Event Bubbling When you don't want the event to reach the parent. In that case, use:
๐ค๐ฃ๐พ๐ก๐๐๐ ={(๐) => { ๐.๐จ๐ฉ๐ค๐ฅ๐๐ง๐ค๐ฅ๐๐๐๐ฉ๐๐ค๐ฃ(); ๐๐ค๐ฃ๐จ๐ค๐ก๐.๐ก๐ค๐("๐ฝ๐ช๐ฉ๐ฉ๐ค๐ฃ ๐๐ก๐๐๐ ๐๐ ๐ค๐ฃ๐ก๐ฎ"); }}Now, clicking the button won't trigger the parent's onClick handler. In an attempt to keep my writing short I'll just give a summary of the benefit of event bubbling:
๐งจEvent bubbling helps you write less code: you can use one one event listener to trigger multiple events
๐งจimprove performance: Fewer event listeners mean less memory usage and faster event processingI hope this was as fun to read as it was to write ๐ฅธ