Skip to content

Commit

Permalink
fix(gatsby-link) fix a memory leak in IntersectionObservers (#17056)
Browse files Browse the repository at this point in the history
* fix(gatsby-link) Clean up IntersectionObserver on componentWillUnmount to prevent memory leaks

Associated issue: #12198

* Check whether IntersectionObserver exists before unobserving
  • Loading branch information
phacks authored and wardpeet committed Aug 28, 2019
1 parent d57f18c commit 762506f
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/gatsby-link/src/index.js
Expand Up @@ -30,7 +30,7 @@ const NavLinkPropTypes = {
}

// Set up IntersectionObserver
const handleIntersection = (el, cb) => {
const createIntersectionObserver = (el, cb) => {
const io = new window.IntersectionObserver(entries => {
entries.forEach(entry => {
if (el === entry.target) {
Expand All @@ -46,6 +46,7 @@ const handleIntersection = (el, cb) => {
})
// Add element to the observer
io.observe(el)
return { instance: io, el }
}

class GatsbyLink extends React.Component {
Expand Down Expand Up @@ -77,6 +78,16 @@ class GatsbyLink extends React.Component {
}
}

componentWillUnmount() {
if (!this.io) {
return
}
const { instance, el } = this.io

instance.unobserve(el)
instance.disconnect()
}

handleRef(ref) {
if (this.props.innerRef && this.props.innerRef.hasOwnProperty(`current`)) {
this.props.innerRef.current = ref
Expand All @@ -86,7 +97,7 @@ class GatsbyLink extends React.Component {

if (this.state.IOSupported && ref) {
// If IO supported and element reference found, setup Observer functionality
handleIntersection(ref, () => {
this.io = createIntersectionObserver(ref, () => {
___loader.enqueue(parsePath(this.props.to).pathname)
})
}
Expand Down

0 comments on commit 762506f

Please sign in to comment.