Skip to content

Instantly share code, notes, and snippets.

@jonidelv
Last active May 26, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonidelv/4f15e0ce08cdfb1cf65c3d047c2642ba to your computer and use it in GitHub Desktop.
Save jonidelv/4f15e0ce08cdfb1cf65c3d047c2642ba to your computer and use it in GitHub Desktop.
React SyntheticEvent

React Events

Things to take into account when working with events in React


When working with DOM events, we have to take care of React's event pooling. Let's explain better what it is: React use a cross-browser wrapper around the browser’s native events called SyntheticEvent. With this wrapper events work identically across all browsers.

Event Pooling

With the SyntheticEvent wrapper, DOM events are pooled. This means that the Event object will be reused, and all properties will be nullified after the event callback has been invoked (React does this for performance reasons) What you need to know as a React developer is: in order to use DOM events in an asynchronous way you need to persist the event. By asynchronous I mean using the event inside promises, throttle/debounce, timeouts and setState operations

Without persist (default behavior: pooled event)

onClick = e => {
  alert(`SYNC -> hasNativeEvent=${!!e.nativeEvent}`)
  setTimeout(() => {
    alert(`ASYNC -> hasNativeEvent=${!!e.nativeEvent}`);
  }, 0)
}

The 2nd (async) will print hasNativeEvent=false because the event properties have been cleaned up.

With persist

onClick = e => {
  e.persist()
  alert(`SYNC -> hasNativeEvent=${!!e.nativeEvent}`)
  setTimeout(() => {
    alert(`ASYNC -> hasNativeEvent=${!!e.nativeEvent}`);
  }, 0)
}

The 2nd (async) will print hasNativeEvent=true because persist allows you to avoid putting the event back in the pool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment