Skip to content

Instantly share code, notes, and snippets.

@jacob-beltran
Last active May 3, 2017 17:39
Show Gist options
  • Save jacob-beltran/84bd0aea2c1023743dda09172d30bc16 to your computer and use it in GitHub Desktop.
Save jacob-beltran/84bd0aea2c1023743dda09172d30bc16 to your computer and use it in GitHub Desktop.
React Performance: Scroll Monitor Example
class ScrollMonitor extends React.Component {
constructor() {
this.handleScrollStart = this.startWatching.bind( this );
this.handleScrollEnd = debounce(
this.stopWatching.bind( this ),
100,
{ leading: false, trailing: true } );
}
componentDidMount() {
window.addEventListener( 'scroll', this.handleScrollStart );
window.addEventListener( 'scroll', this.handleScrollEnd );
}
componentWillUnmount() {
window.removeEventListener( 'scroll', this.handleScrollStart );
window.removeEventListener( 'scroll', this.handleScrollEnd );
//Make sure the loop doesn't run anymore if component is unmounted
this.stopWatching();
}
// If the watchloop isn't running start it
startWatching() {
if( !this._watchFrame ) {
this.watchLoop();
}
}
// Cancel the next iteration of the watch loop
stopWatching() {
window.cancelAnimationFrame( this._watchFrame );
}
// Keep running on each animation frame untill stopped.
watchLoop() {
this.doThingYouWantToWatchForExampleScrollPositionOrWhatever()
this._watchFrame = window.requestAnimationFrame( this.watchLoop )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment