Unverified Commit ec430ea7 authored by Tyler Deitz's avatar Tyler Deitz Committed by GitHub

Fix memory leak in useIntersection (#20407)

This pull request adds an `elements.delete` operation to the `useIntersection`'s cleanup function: `unobserve`.

Without this delete operation, next.js holds onto an unreachable reference of every observed element indefinitely (automatically every Link and Image is observed, so that means every rendered Link and Image element adds to the leak). I found this memory leak when building out an infinite feed in next.js with thousands of Link elements.

The final code block of the `unobserve` function body:

```tsx
  // Destroy observer when there's nothing left to watch:
  if (elements.size === 0) {
    observer.disconnect()
    observers.delete(id)
  }
```

Is effectively unreachable without this delete operation, as the `elements` map will never decrease in size as it is currently. This means that there will always be at least one IntersectionObserver instance in memory if useIntersection has been used once, regardless of if there are currently any components still using the hook.
parent d1c56590
...@@ -55,6 +55,7 @@ function observe( ...@@ -55,6 +55,7 @@ function observe(
observer.observe(element) observer.observe(element)
return function unobserve() { return function unobserve() {
elements.delete(element)
observer.unobserve(element) observer.unobserve(element)
// Destroy observer when there's nothing left to watch: // Destroy observer when there's nothing left to watch:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment