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 )
}
}