Skip to content

Commit

Permalink
Merge pull request #265 from brigade/async-update
Browse files Browse the repository at this point in the history
Defer `handleScroll` in `componentDidUpdate`
  • Loading branch information
lencioni authored Jul 12, 2018
2 parents 5e3ec79 + 62a4225 commit f4967bf
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/waypoint.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,11 @@ export default class Waypoint extends BaseClass {
}

// this._ref may occasionally not be set at this time. To help ensure that
// this works smoothly, we want to delay the initial execution until the
// next tick.
this.cancelInitialTimeout = onNextTick(() => {
// this works smoothly and to avoid layout thrashing, we want to delay the
// initial execution until the next tick.
this.cancelOnNextTick = onNextTick(() => {
this.cancelOnNextTick = null;

// Berofe doing anything, we want to check that this._ref is avaliable in Waypoint
ensureRefIsUsedByChild(this.props.children, this._ref);

Expand Down Expand Up @@ -90,8 +92,21 @@ export default class Waypoint extends BaseClass {
return;
}

// The element may have moved.
this._handleScroll(null);
// The element may have moved, so we need to recompute its position on the
// page. This happens via handleScroll in a way that forces layout to be
// computed.
//
// We want this to be deferred to avoid forcing layout during render, which
// causes layout thrashing. And, if we already have this work enqueued, we
// can just wait for that to happen instead of enqueueing again.
if (this.cancelOnNextTick) {
return;
}

this.cancelOnNextTick = onNextTick(() => {
this.cancelOnNextTick = null;
this._handleScroll(null);
});
}

componentWillUnmount() {
Expand All @@ -106,8 +121,8 @@ export default class Waypoint extends BaseClass {
this.resizeEventListenerUnsubscribe();
}

if (this.cancelInitialTimeout) {
this.cancelInitialTimeout();
if (this.cancelOnNextTick) {
this.cancelOnNextTick();
}
}

Expand Down

0 comments on commit f4967bf

Please sign in to comment.