Last active
May 3, 2017 17:39
-
-
Save jacob-beltran/84bd0aea2c1023743dda09172d30bc16 to your computer and use it in GitHub Desktop.
React Performance: Scroll Monitor Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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