Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix <Image/>'s lazyRoot and other optimizations #37447

Merged
merged 18 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 35 additions & 35 deletions packages/next/client/use-intersection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Observer = {
elements: Map<Element, ObserveCallback>
}

const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'
const hasIntersectionObserver = typeof IntersectionObserver === 'function'
SukkaW marked this conversation as resolved.
Show resolved Hide resolved

export function useIntersection<T extends Element>({
rootRef,
Expand All @@ -34,43 +34,46 @@ export function useIntersection<T extends Element>({

const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false)
const [root, setRoot] = useState(rootRef ? rootRef.current : null)
const setRef = useCallback(
(el: T | null) => {
const elementRef = useRef<T | null>(null)

useEffect(() => {
if (hasIntersectionObserver) {
if (unobserve.current) {
unobserve.current()
unobserve.current = undefined
}

if (isDisabled || visible) return

const el = elementRef.current
if (el && el.tagName) {
unobserve.current = observe(
el,
(isVisible) => isVisible && setVisible(isVisible),
{ root, rootMargin }
{ root: rootRef?.current, rootMargin }
)
}
},
[isDisabled, root, rootMargin, visible]
)

const resetVisible = useCallback(() => {
setVisible(false)
}, [])

useEffect(() => {
if (!hasIntersectionObserver) {
return () => {
unobserve.current?.()
unobserve.current = undefined
}
} else {
if (!visible) {
const idleCallback = requestIdleCallback(() => setVisible(true))
return () => cancelIdleCallback(idleCallback)
}
}
}, [visible])
}, [isDisabled, rootMargin, rootRef, visible])

const resetVisible = useCallback(() => {
setVisible(false)
}, [])

const setRef = useCallback((el: T | null) => {
elementRef.current = el
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we still need to store the element reference in a useState() since when setRef is called we update the reference here but we aren't re-calling the useEffect above so we won't observe the new ref unless the parent component re-renders?

Or are we changing this hook to have the assumption that the ref passed to setRef should always only change when the parent re-renders?

Copy link
Contributor Author

@SukkaW SukkaW Jun 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we still need to store the element reference in a useState() since when setRef is called we update the reference here but we aren't re-calling the useEffect above so we won't observe the new ref unless the parent component re-renders?

Or are we changing this hook to have the assumption that the ref passed to setRef should always only change when the parent re-renders?

Here is what I thought. setRef here is only supposed to be called after component mounts. In <Image /> and <Link /> case, it is called inside the callback ref.

And the assumption here is that the DOM node itself would remain the same after the component mounts and before unmounts.

Copy link
Contributor Author

@SukkaW SukkaW Jun 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After reading the React documentation again, updating a state inside a callback ref might not be a bad idea after all: How can I measure a DOM node? - Hooks FAQ.

I will change it to store the element reference in a state instead.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about a test to count renders? #37447 (review)

Copy link
Contributor Author

@SukkaW SukkaW Jun 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about a test to count renders? #37447 (review)

@styfle I still have no idea how to test this. It is almost impossible to test against component update counts.

One way is to patch the React reconciler through SECRET_INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.

Another way is to add a global variable but it will have to live inside the next/image component, introducing completely useless bytes in the production. The global variable just can't live inside the test case, because when a component re-renders, its parent components will not always re-render.

Copy link
Member

@styfle styfle Jun 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about globalThis._testRenderCount so that its global and doesnt live inside a component and therefor outside of React's jurisdiction

Copy link
Contributor Author

@SukkaW SukkaW Jun 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about globalThis._testRenderCount so that its global and doesnt live inside a component and therefor outside of React's jurisdiction

globalThis._testRenderCount does live outside of React, but the modification of this variable has to live inside the next/image component (and probably has to be inside a useEffect), which is what I am really concerned about.

As I said before, when a component re-renders, its parent components will not always re-render, thus we can't add the globalThis._testRenderCount modification in <Image />'s parent component (it can't reflect how many times the child component has been updated).

}, [])

useEffect(() => {
if (rootRef) setRoot(rootRef.current)
}, [rootRef])
return [setRef, visible, resetVisible]
}

Expand All @@ -91,7 +94,7 @@ function observe(
if (elements.size === 0) {
observer.disconnect()
observers.delete(id)
let index = idList.findIndex(
const index = idList.findIndex(
(obj) => obj.root === id.root && obj.margin === id.margin
)
if (index > -1) {
Expand All @@ -110,18 +113,16 @@ function createObserver(options: UseIntersectionObserverInit): Observer {
root: options.root || null,
margin: options.rootMargin || '',
}
let existing = idList.find(
const existing = idList.find(
(obj) => obj.root === id.root && obj.margin === id.margin
)
let instance
let instance: Observer | undefined

if (existing) {
instance = observers.get(existing)
} else {
instance = observers.get(id)
idList.push(id)
}
styfle marked this conversation as resolved.
Show resolved Hide resolved
if (instance) {
return instance
if (instance) {
return instance
}
}

const elements = new Map<Element, ObserveCallback>()
Expand All @@ -134,14 +135,13 @@ function createObserver(options: UseIntersectionObserverInit): Observer {
}
})
}, options)

observers.set(
instance = {
id,
(instance = {
id,
observer,
elements,
})
)
observer,
elements,
}

idList.push(id)
observers.set(id, instance)
return instance
}
4 changes: 0 additions & 4 deletions test/integration/image-component/basic/pages/lazy.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'

const Lazy = () => {
return (
Expand Down Expand Up @@ -54,9 +53,6 @@ const Lazy = () => {
width={800}
lazyBoundary="0px 0px 500px 0px"
></Image>
<Link href="/missing-observer">
<a id="observerlink">observer</a>
</Link>
</div>
)
}
Expand Down
28 changes: 0 additions & 28 deletions test/integration/image-component/basic/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -384,19 +384,6 @@ describe('Image Component Tests', () => {
browser = null
})
lazyLoadingTests()
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/missing-observer')
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
describe('Client-side Lazy Loading Tests', () => {
beforeAll(async () => {
Expand All @@ -408,20 +395,5 @@ describe('Image Component Tests', () => {
browser = null
})
lazyLoadingTests()
it('should automatically load images if observer does not exist', async () => {
await browser.waitForElementByCss('#observerlink').click()
await waitFor(500)
browser = await webdriver(appPort, '/missing-observer')
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
path: 'https://example.com/myaccount/',
loader: 'imgix',
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
render() {
return (
<Html>
<Head crossOrigin="anonymous">
<script
dangerouslySetInnerHTML={{ __html: 'IntersectionObserver = null' }}
/>
styfle marked this conversation as resolved.
Show resolved Hide resolved
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Link from 'next/link'

const About = () => {
return (
<div>
<Link href="/no-observer">
<a id="link-no-observer">Test No IntersectionObserver</a>
</Link>
</div>
)
}

export default About
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import React, { useLayoutEffect } from 'react'
import Image from 'next/image'

const Lazy = () => {
useLayoutEffect(() => {
IntersectionObserver = null //eslint-disable-line
})
return (
<div>
<p id="stubtext">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import {
check,
findPort,
killApp,
nextBuild,
nextStart,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'

const appDir = join(__dirname, '../')
let appPort
let app
let browser

describe('Image Component No IntersectionObserver test', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))

describe('SSR Lazy Loading Tests', () => {
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/no-observer')

// Make sure the IntersectionObserver is mocked to null during the test
await check(() => {
return browser.eval('IntersectionObserver')
}, /null/)

expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})

describe('Client-side Lazy Loading Tests', () => {
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/')

// Make sure the IntersectionObserver is mocked to null during the test
await check(() => {
return browser.eval('IntersectionObserver')
}, /null/)

await browser.waitForElementByCss('#link-no-observer').click()

await waitFor(1000)
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
})