What is event pooling in react?

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

refer : Event System in React

Event Pooling
React uses SyntheticEvent which is a wrapper for native browser events so that they have consistent properties across different browsers. The event handlers that we have in any react-app are actually passed instances of SyntheticEvent unless we use nativeEvent attribute to get the underlying browser event.

Wrapping native event instances can cause performance issues since every synthetic event wrapper that’s created will also need to be garbage collected at some point, which can be expensive in terms of CPU time.

React deals with this problem by allocating a synthetic instance pool. Whenever an event is triggered, it takes an instance from the pool and populates its properties and reuses it. When the event handler has finished running, all properties will be nullified and the synthetic event instance is released back into the pool. Hence, increasing the performance.

It means that the properties of the event only exist while the callback is active. Adding async to the mix, or storing the event for future use, will fail.

This is easily observed if you try console.log(event) inside an event handler. By the time you inspect the object, most properties on the event object will be null. If you stop execution of the script with debugger; immediately after logging the value, you can inspect the values.

class MyComponent extends React.Component {
    handleClick (e){
    console.log('The event currentTarget is', e.currentTarget); // DOM element
    setTimeout(() => {
    console.log('event.currentTarget was', e.currentTarget); // null
  }, 1000)
  render () {
    return <button onClick={this.handleClick}>Fire event!</button>

This will log a DOM element when you click the button, and null a second later. For reasons beyond me, event.target is still stored until the next event occurs, and not nullified.

Read More:   How to detect if a request was aborted?

Be informed that event pooling is removed from React 17, citing the below reason.

React 17 removes the “event pooling” optimization from React. It doesn’t improve performance in modern browsers and confuses even experienced React users


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts