In reactJS, when an event occurs it is propagated from the innermost element that triggered the event to its parent elements, until it reaches the topmost element in the DOM. This is also known as the ‘event bubbling‘.

There are some cases, where we don’t want the events get propagated to the parent elements. In such a case, we use the stopPropagation.

Following is the example:

function handleClick(event) {
  event.stopPropagation();
  console.log('Button clicked!');
}

function Container() {
  function handleContainerClick() {
    console.log('Container clicked!');
  }

  return (
    <div onClick={handleContainerClick}>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

In the above example, we have a button inside a container. When the button is clicked, we want to prevent the container’s onClick event from being triggered. To achieve this, we call stopPropagation() on the button’s onClick event.

If we didn’t call stopPropagation(), both the button’s onClick event and the container’s onClick event would be triggered when the button is clicked.

When to use stopPropagation()?

Preventing conflicts with other event listeners: If we have multiple event listeners attached to the same element, and you want to prevent them from interfering with each other, we can use stopPropagation() to isolate the events.

Improving performance: When we have a large number of event listeners attached to a parent element, and if we only need to handle the event on the child element, calling stopPropagation() can improve performance by preventing unnecessary event propagation.

Categorized in:

Tagged in: