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

Conversation

SukkaW
Copy link
Contributor

@SukkaW SukkaW commented Jun 4, 2022

The PR fixes <Image /> and <Link /> components' extra re-renders, lazyRoot has no effect, and applies some other optimizations.

@ijjk

This comment was marked as outdated.

@SukkaW SukkaW force-pushed the use-intersection-optimize branch from 7584b12 to 4416195 Compare June 5, 2022 10:15
@ijjk

This comment was marked as outdated.

@SukkaW SukkaW force-pushed the use-intersection-optimize branch from 4416195 to 031166c Compare June 5, 2022 10:35
Comment on lines 39 to 55
useEffect(() => {
if (unobserve.current) {
unobserve.current()
unobserve.current = undefined
}

if (el && el.tagName) {
unobserve.current = observe(
el,
(isVisible) => isVisible && setVisible(isVisible),
{ root, rootMargin }
)
}
},
[isDisabled, root, rootMargin, visible]
)
if (isDisabled || visible) return

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

@SukkaW SukkaW Jun 5, 2022

Choose a reason for hiding this comment

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

Before the PR

  • setIntersection is used in <Image />'s callback ref, which will be called when <Image /> is first mounted.
  • During setIntersection, an IntersectionObserver instance is created and it observes the HTMLImageElement with rootRef.current is still null
  • By the time <Image /> is mounted, its parent element (lazyRoot) hasn't been mounted yet, so lazyRoot has a value of { current: null }.
  • By the time the setRoot effect is committed, an IntersectionObserver instance is already created, and the lazyRoot is never applied to the IntersectionObserver instance

After the PR

  • setIntersection is used in <Image />'s callback ref, which will be called when <Image /> is first mounted.
  • During setIntersection, the HTMLImageElement is synced to a ref (use ref instead of state to prevent extra re-rendering)
  • By the time useEffect commits the effect, lazyRoot is already mounted, and the elementRef.current also exists (it is set during <Image /> mounting)
  • Only then (during the effect) the observer is created with lazyRoot applied.

In short: The IntersectionObserver is a web API (DOM API) and should be considered as a side-effect. A side-effect shouldn't be executed inside DOM's callback ref.

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 adding a test for lazyRoot?

@SukkaW SukkaW changed the title Fix <Image/> & <Link/> re-renders and other optimizations Fix <Image/>'s lazyRoot and other optimizations Jun 5, 2022
@SukkaW SukkaW force-pushed the use-intersection-optimize branch from 4d1efed to 8b95254 Compare June 5, 2022 11:16
@SukkaW SukkaW force-pushed the use-intersection-optimize branch from 8b95254 to f2df42b Compare June 5, 2022 11:49
@SukkaW SukkaW force-pushed the use-intersection-optimize branch from 7367e0d to b90dd29 Compare June 6, 2022 05:48
@SukkaW SukkaW force-pushed the use-intersection-optimize branch from b90dd29 to 36e7ed7 Compare June 6, 2022 06:10
Copy link
Member

@styfle styfle left a comment

Choose a reason for hiding this comment

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

Can you add a test to verify that this fixes the extra re-renders?

@11koukou
Copy link
Contributor

11koukou commented Jun 6, 2022

Hello again! It's been some time since the #33933 PR. What I am sure about is that it worked as intended and that the test was proving correctly the functionality.

As far as I have understood this issue has to do with performance/ re-rendering, correct me If I am wrong. If you need anything specific please mention me since these days I have little to no time spending reviewing and testing everything again, but I am willing if it's urgent.

Finally, according to my experience I want to tell that trying to correct React's too many renders, often leads to worse overall performance and that great attention must be payed to that kind of fixes. That means that often it's better to leave React do it's job even with more re-renders. Tools like react devtools in chrome can show accurately in milliseconds how much each react's commit costs. However I want to assure that I had not thoroughly tested my pr in terms of performance and that it's more than likely that it needs (heavy) optimization.

Thank you

@SukkaW
Copy link
Contributor Author

SukkaW commented Jun 7, 2022

Can you add a test to verify that this fixes the extra re-renders?

I am wondering if it is possible to test against the rendering counts of a component with the existing test suite. Do Next.js integration test cases have some existing examples?

Hello again! It's been some time since the #33933 PR. What I am sure about is that it worked as intended and that the test was proving correctly the functionality.

Yeah, your PR is sound and working as intended. This PR just also removes some redundant code introduced from your PR.

@styfle
Copy link
Member

styfle commented Jun 7, 2022

Here's an example test:

it('should callback onLoadingComplete when image is fully loaded', async () => {

and the corresponding test fixture (its just a page):

const [idToCount, setIdToCount] = useState({})

Although its probably best to use a global variable let count = 0 instead of setState() just to verify the number of function calls regardless of React's implementation of state.

@SukkaW
Copy link
Contributor Author

SukkaW commented Jun 7, 2022

Here's an example test:

Although its probably best to use a global variable let count = 0 instead of setState() just to verify the number of function calls regardless of React's implementation of state.

Thanks! But that test is based on next/image already exposed a prop callback (onLoadingComplete), and it is testing against how many times props.onLoadingComplete is called, not how many times the component itself is being rendered.

I have found a testing library react-performance-testing, but it would patch the React in order to get rendering counts (which I am afraid is an anti-pattern, since React internal API might / would change from time to time).

@SukkaW SukkaW requested a review from styfle June 7, 2022 04:24
Copy link
Member

@styfle styfle left a comment

Choose a reason for hiding this comment

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

Looks good to me, thanks!

Also how about a test with a global variable let count = 0 just to verify the number of renders?

cc @ijjk @timneutkens for additional review here since this code is critical to all Next.js apps

}, [])

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).

@SukkaW SukkaW requested review from ijjk and styfle June 14, 2022 04:47
@kodiakhq kodiakhq bot merged commit ad728f4 into vercel:canary Jun 21, 2022
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jul 22, 2022
@SukkaW SukkaW deleted the use-intersection-optimize branch October 24, 2023 08:34
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants