What is event pooling in react?
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.
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.
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
https://reactjs.org/blog/2020/08/10/react-v17-rc.html#no-event-pooling