Skip to content

Commit 2f40b0a

Browse files
fix(gatsby-react-router-scroll): debounce function for scollListener (#26933)
Co-authored-by: Ward Peeters <[email protected]>
1 parent 002aae6 commit 2f40b0a

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

e2e-tests/production-runtime/cypress/integration/scroll-behavior.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ describe(`Scroll behaviour`, () => {
4444
expect(win.scrollY).not.to.eq(0, 0)
4545

4646
cy.scrollTo(`bottom`)
47+
cy.wait(500) // allow ScrollContext to update scroll position store
4748
cy.go(`back`).waitForRouteChange()
4849
cy.go(`forward`).waitForRouteChange()
4950

packages/gatsby-react-router-scroll/src/scroll-handler.tsx

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,29 @@ export class ScrollHandler extends React.Component<
2525

2626
_stateStorage: SessionStorage = new SessionStorage()
2727

28+
// @see https://www.html5rocks.com/en/tutorials/speed/animations/
29+
_isTicking = false
30+
_latestKnownScrollY = 0
2831
scrollListener = (): void => {
29-
const { key } = this.props.location
32+
this._latestKnownScrollY = window.scrollY
33+
34+
if (!this._isTicking) {
35+
this._isTicking = true
36+
requestAnimationFrame(this._saveScroll.bind(this))
37+
}
38+
}
39+
40+
_saveScroll(): void {
41+
const key = this.props.location.key || null
3042

3143
if (key) {
32-
this._stateStorage.save(this.props.location, key, window.scrollY)
44+
this._stateStorage.save(
45+
this.props.location,
46+
key,
47+
this._latestKnownScrollY
48+
)
3349
}
50+
this._isTicking = false
3451
}
3552

3653
componentDidMount(): void {

0 commit comments

Comments
 (0)