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 multiple calls to image onLoadingComplete() #33474

Merged
merged 11 commits into from
Jan 20, 2022

Conversation

styfle
Copy link
Member

@styfle styfle commented Jan 19, 2022

The image prop onLoadingComplete() was unexpectedly called multiple times because it uses a callback ref.

This could lead to an infinite loop if onLoadingComplete() calls setState() as demonstrated in the updated test.

The solution is to handle refs with useRef() and useEffect so onLoadingComplete() is called at most once per component instance.

ijjk
ijjk previously approved these changes Jan 19, 2022
Co-authored-by: JJ Kasper <jj@jjsweb.site>
ijjk
ijjk previously approved these changes Jan 19, 2022
@ijjk

This comment has been minimized.

@ijjk
Copy link
Member

ijjk commented Jan 19, 2022

Failing test suites

Commit: ec6ee05

test/integration/image-component/default/test/index.test.js

  • Image Component Tests > dev mode > should callback onLoadingComplete when image is fully loaded
  • Image Component Tests > server mode > should callback onLoadingComplete when image is fully loaded
  • Image Component Tests > serverless mode > should callback onLoadingComplete when image is fully loaded
Expand output

● Image Component Tests › dev mode › should callback onLoadingComplete when image is fully loaded

TIMED OUT: loaded 1 img6 with dimensions 3x5

loaded 1 img6 with dimensions 1x1

  479 | }
  480 |
> 481 | export class File {
      |               ^
  482 |   constructor(path) {
  483 |     this.path = path
  484 |     this.originalContent = existsSync(this.path)

  at Object.check (lib/next-test-utils.js:481:15)
  at Object.<anonymous> (integration/image-component/default/test/index.test.js:163:13)

● Image Component Tests › server mode › should callback onLoadingComplete when image is fully loaded

TIMED OUT: loaded 1 img6 with dimensions 3x5

loaded 1 img6 with dimensions 1x1

  479 | }
  480 |
> 481 | export class File {
      |               ^
  482 |   constructor(path) {
  483 |     this.path = path
  484 |     this.originalContent = existsSync(this.path)

  at Object.check (lib/next-test-utils.js:481:15)
  at Object.<anonymous> (integration/image-component/default/test/index.test.js:163:13)

● Image Component Tests › serverless mode › should callback onLoadingComplete when image is fully loaded

TIMED OUT: loaded 1 img6 with dimensions 3x5

loaded 1 img6 with dimensions 1x1

  479 | }
  480 |
> 481 | export class File {
      |               ^
  482 |   constructor(path) {
  483 |     this.path = path
  484 |     this.originalContent = existsSync(this.path)

  at Object.check (lib/next-test-utils.js:481:15)
  at Object.<anonymous> (integration/image-component/default/test/index.test.js:163:13)

@ijjk

This comment has been minimized.

@ijjk

This comment has been minimized.

packages/next/client/image.tsx Outdated Show resolved Hide resolved
packages/next/client/image.tsx Show resolved Hide resolved
@styfle styfle requested review from shuding and ijjk January 20, 2022 01:52
@ijjk

This comment has been minimized.

@ijjk
Copy link
Member

ijjk commented Jan 20, 2022

Stats from current PR

Default Build (Increase detected ⚠️)
General Overall increase ⚠️
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
buildDuration 14.8s 14.6s -206ms
buildDurationCached 3.3s 3.2s -57ms
nodeModulesSize 355 MB 355 MB ⚠️ +2.3 kB
Page Load Tests Overall increase ✓
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
/ failed reqs 0 0
/ total time (seconds) 2.993 3.062 ⚠️ +0.07
/ avg req/sec 835.39 816.33 ⚠️ -19.06
/error-in-render failed reqs 0 0
/error-in-render total time (seconds) 1.459 1.44 -0.02
/error-in-render avg req/sec 1713.17 1736.33 +23.16
Client Bundles (main, webpack, commons)
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
450.HASH.js gzip 179 B 179 B
framework-HASH.js gzip 42.2 kB 42.2 kB
main-HASH.js gzip 27.2 kB 27.2 kB
webpack-HASH.js gzip 1.44 kB 1.44 kB
Overall change 71 kB 71 kB
Legacy Client Bundles (polyfills)
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
polyfills-HASH.js gzip 31 kB 31 kB
Overall change 31 kB 31 kB
Client Pages Overall increase ⚠️
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
_app-HASH.js gzip 1.37 kB 1.37 kB
_error-HASH.js gzip 194 B 194 B
amp-HASH.js gzip 312 B 312 B
css-HASH.js gzip 326 B 326 B
dynamic-HASH.js gzip 2.37 kB 2.37 kB
head-HASH.js gzip 350 B 350 B
hooks-HASH.js gzip 919 B 919 B
image-HASH.js gzip 4.7 kB 4.87 kB ⚠️ +171 B
index-HASH.js gzip 263 B 263 B
link-HASH.js gzip 2.13 kB 2.13 kB
routerDirect..HASH.js gzip 321 B 321 B
script-HASH.js gzip 383 B 383 B
withRouter-HASH.js gzip 318 B 318 B
85e02e95b279..7e3.css gzip 107 B 107 B
Overall change 14.1 kB 14.2 kB ⚠️ +171 B
Client Build Manifests
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
_buildManifest.js gzip 459 B 459 B
Overall change 459 B 459 B
Rendered Page Sizes
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
index.html gzip 531 B 531 B
link.html gzip 545 B 545 B
withRouter.html gzip 526 B 526 B
Overall change 1.6 kB 1.6 kB

Diffs

Diff for _buildManifest.js
@@ -12,7 +12,7 @@ self.__BUILD_MANIFEST = {
   ],
   "/head": ["static\u002Fchunks\u002Fpages\u002Fhead-7100d3b2a548f0e4.js"],
   "/hooks": ["static\u002Fchunks\u002Fpages\u002Fhooks-538d621a0e670391.js"],
-  "/image": ["static\u002Fchunks\u002Fpages\u002Fimage-40f32eb1d96a561c.js"],
+  "/image": ["static\u002Fchunks\u002Fpages\u002Fimage-7c12d79b5adf878e.js"],
   "/link": ["static\u002Fchunks\u002Fpages\u002Flink-1339957a75cc3c85.js"],
   "/routerDirect": [
     "static\u002Fchunks\u002Fpages\u002FrouterDirect-76232dd6bc335a24.js"
Diff for image-HASH.js
@@ -127,7 +127,7 @@
         value: true
       };
       exports["default"] = Image;
-      var _react = _interopRequireDefault(__webpack_require__(7294));
+      var _react = _interopRequireWildcard(__webpack_require__(7294));
       var _head = _interopRequireDefault(__webpack_require__(5443));
       var _imageConfig = __webpack_require__(5809);
       var _useIntersection = __webpack_require__(7190);
@@ -151,6 +151,30 @@
               default: obj
             };
       }
+      function _interopRequireWildcard(obj) {
+        if (obj && obj.__esModule) {
+          return obj;
+        } else {
+          var newObj = {};
+          if (obj != null) {
+            for (var key in obj) {
+              if (Object.prototype.hasOwnProperty.call(obj, key)) {
+                var desc =
+                  Object.defineProperty && Object.getOwnPropertyDescriptor
+                    ? Object.getOwnPropertyDescriptor(obj, key)
+                    : {};
+                if (desc.get || desc.set) {
+                  Object.defineProperty(newObj, key, desc);
+                } else {
+                  newObj[key] = obj[key];
+                }
+              }
+            }
+          }
+          newObj.default = obj;
+          return newObj;
+        }
+      }
       function _objectSpread(target) {
         var _arguments = arguments,
           _loop = function(i) {
@@ -201,7 +225,6 @@
         }
         return target;
       }
-      var loadedImageURLs = new Set();
       var allImgs = new Map();
       var perfObserver;
       var emptyDataURL =
@@ -398,27 +421,36 @@
       }
       // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
       // handler instead of the img's onLoad attribute.
-      function handleLoading(img, src, layout, placeholder, onLoadingComplete) {
-        if (!img) {
-          return;
-        }
+      function handleLoading(
+        imgRef,
+        src,
+        layout,
+        placeholder,
+        onLoadingCompleteRef
+      ) {
         var handleLoad = function() {
+          var img = imgRef.current;
+          if (!img) {
+            return;
+          }
           if (img.src !== emptyDataURL) {
             var p = "decode" in img ? img.decode() : Promise.resolve();
             p.catch(function() {}).then(function() {
+              if (!imgRef.current) {
+                return;
+              }
               if (placeholder === "blur") {
                 img.style.filter = "";
                 img.style.backgroundSize = "";
                 img.style.backgroundImage = "";
                 img.style.backgroundPosition = "";
               }
-              loadedImageURLs.add(src);
-              if (onLoadingComplete) {
+              if (onLoadingCompleteRef.current) {
                 var naturalWidth = img.naturalWidth,
                   naturalHeight = img.naturalHeight;
                 // Pass back read-only primitive values but not the
                 // underlying DOM element because it could be misused.
-                onLoadingComplete({
+                onLoadingCompleteRef.current({
                   naturalWidth: naturalWidth,
                   naturalHeight: naturalHeight
                 });
@@ -429,13 +461,15 @@
             });
           }
         };
-        if (img.complete) {
-          // If the real image fails to load, this will still remove the placeholder.
-          // This is the desired behavior for now, and will be revisited when error
-          // handling is worked on for the image component itself.
-          handleLoad();
-        } else {
-          img.onload = handleLoad;
+        if (imgRef.current) {
+          if (imgRef.current.complete) {
+            // If the real image fails to load, this will still remove the placeholder.
+            // This is the desired behavior for now, and will be revisited when error
+            // handling is worked on for the image component itself.
+            handleLoad();
+          } else {
+            imgRef.current.onload = handleLoad;
+          }
         }
       }
       function Image(_param) {
@@ -478,6 +512,8 @@
             "placeholder",
             "blurDataURL"
           ]);
+        var ref4;
+        var imgRef = (0, _react).useRef(null);
         var rest = all;
         var layout = sizes ? "responsive" : "intrinsic";
         if ("layout" in rest) {
@@ -521,7 +557,12 @@
           unoptimized = true;
           isLazy = false;
         }
-        if (true && loadedImageURLs.has(src)) {
+        if (
+          true &&
+          ((ref4 = imgRef.current) === null || ref4 === void 0
+            ? void 0
+            : ref4.complete)
+        ) {
           isLazy = false;
         }
         if (false) {
@@ -534,7 +575,7 @@
             }),
             2
           ),
-          setRef = ref3[0],
+          setIntersection = ref3[0],
           isIntersected = ref3[1];
         var isVisible = !isLazy || isIntersected;
         var wrapperStyle = {
@@ -667,6 +708,32 @@
           _defineProperty(_obj, imageSrcSetPropName, imgAttributes.srcSet),
           _defineProperty(_obj, imageSizesPropName, imgAttributes.sizes),
           _obj);
+        var useLayoutEffect = false ? 0 : _react.default.useLayoutEffect;
+        var onLoadingCompleteRef = (0, _react).useRef(onLoadingComplete);
+        (0, _react).useEffect(
+          function() {
+            onLoadingCompleteRef.current = onLoadingComplete;
+          },
+          [onLoadingComplete]
+        );
+        useLayoutEffect(
+          function() {
+            setIntersection(imgRef.current);
+          },
+          [setIntersection]
+        );
+        (0, _react).useEffect(
+          function() {
+            handleLoading(
+              imgRef,
+              srcString,
+              layout,
+              placeholder,
+              onLoadingCompleteRef
+            );
+          },
+          [srcString, layout, placeholder, isVisible]
+        );
         return /*#__PURE__*/ _react.default.createElement(
           "span",
           {
@@ -704,16 +771,7 @@
               decoding: "async",
               "data-nimg": layout,
               className: className,
-              ref: function(img) {
-                setRef(img);
-                handleLoading(
-                  img,
-                  srcString,
-                  layout,
-                  placeholder,
-                  onLoadingComplete
-                );
-              },
+              ref: imgRef,
               style: _objectSpread({}, imgStyle, blurStyle)
             })
           ),

Default Build with SWC (Increase detected ⚠️)
General Overall increase ⚠️
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
buildDuration 18.4s 18s -369ms
buildDurationCached 3.3s 3.2s -59ms
nodeModulesSize 355 MB 355 MB ⚠️ +2.3 kB
Page Load Tests Overall increase ✓
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
/ failed reqs 0 0
/ total time (seconds) 3.02 2.964 -0.06
/ avg req/sec 827.75 843.51 +15.76
/error-in-render failed reqs 0 0
/error-in-render total time (seconds) 1.442 1.376 -0.07
/error-in-render avg req/sec 1733.43 1817.31 +83.88
Client Bundles (main, webpack, commons)
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
450.HASH.js gzip 179 B 179 B
framework-HASH.js gzip 42.3 kB 42.3 kB
main-HASH.js gzip 27.3 kB 27.3 kB
webpack-HASH.js gzip 1.44 kB 1.44 kB
Overall change 71.3 kB 71.3 kB
Legacy Client Bundles (polyfills)
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
polyfills-HASH.js gzip 31 kB 31 kB
Overall change 31 kB 31 kB
Client Pages Overall increase ⚠️
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
_app-HASH.js gzip 1.35 kB 1.35 kB
_error-HASH.js gzip 180 B 180 B
amp-HASH.js gzip 305 B 305 B
css-HASH.js gzip 321 B 321 B
dynamic-HASH.js gzip 2.36 kB 2.36 kB
head-HASH.js gzip 342 B 342 B
hooks-HASH.js gzip 911 B 911 B
image-HASH.js gzip 4.73 kB 4.88 kB ⚠️ +155 B
index-HASH.js gzip 256 B 256 B
link-HASH.js gzip 2.19 kB 2.19 kB
routerDirect..HASH.js gzip 314 B 314 B
script-HASH.js gzip 375 B 375 B
withRouter-HASH.js gzip 309 B 309 B
85e02e95b279..7e3.css gzip 107 B 107 B
Overall change 14.1 kB 14.2 kB ⚠️ +155 B
Client Build Manifests
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
_buildManifest.js gzip 459 B 459 B
Overall change 459 B 459 B
Rendered Page Sizes
vercel/next.js canary vercel/next.js fix-infinite-on-loading-complete Change
index.html gzip 532 B 532 B
link.html gzip 545 B 545 B
withRouter.html gzip 526 B 526 B
Overall change 1.6 kB 1.6 kB

Diffs

Diff for _buildManifest.js
@@ -12,7 +12,7 @@ self.__BUILD_MANIFEST = {
   ],
   "/head": ["static\u002Fchunks\u002Fpages\u002Fhead-7100d3b2a548f0e4.js"],
   "/hooks": ["static\u002Fchunks\u002Fpages\u002Fhooks-538d621a0e670391.js"],
-  "/image": ["static\u002Fchunks\u002Fpages\u002Fimage-40f32eb1d96a561c.js"],
+  "/image": ["static\u002Fchunks\u002Fpages\u002Fimage-7c12d79b5adf878e.js"],
   "/link": ["static\u002Fchunks\u002Fpages\u002Flink-1339957a75cc3c85.js"],
   "/routerDirect": [
     "static\u002Fchunks\u002Fpages\u002FrouterDirect-76232dd6bc335a24.js"
Diff for image-HASH.js
@@ -127,7 +127,7 @@
         value: true
       };
       exports["default"] = Image;
-      var _react = _interopRequireDefault(__webpack_require__(7294));
+      var _react = _interopRequireWildcard(__webpack_require__(7294));
       var _head = _interopRequireDefault(__webpack_require__(5443));
       var _imageConfig = __webpack_require__(5809);
       var _useIntersection = __webpack_require__(7190);
@@ -151,6 +151,30 @@
               default: obj
             };
       }
+      function _interopRequireWildcard(obj) {
+        if (obj && obj.__esModule) {
+          return obj;
+        } else {
+          var newObj = {};
+          if (obj != null) {
+            for (var key in obj) {
+              if (Object.prototype.hasOwnProperty.call(obj, key)) {
+                var desc =
+                  Object.defineProperty && Object.getOwnPropertyDescriptor
+                    ? Object.getOwnPropertyDescriptor(obj, key)
+                    : {};
+                if (desc.get || desc.set) {
+                  Object.defineProperty(newObj, key, desc);
+                } else {
+                  newObj[key] = obj[key];
+                }
+              }
+            }
+          }
+          newObj.default = obj;
+          return newObj;
+        }
+      }
       function _objectSpread(target) {
         var _arguments = arguments,
           _loop = function(i) {
@@ -201,7 +225,6 @@
         }
         return target;
       }
-      var loadedImageURLs = new Set();
       var allImgs = new Map();
       var perfObserver;
       var emptyDataURL =
@@ -398,27 +421,36 @@
       }
       // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
       // handler instead of the img's onLoad attribute.
-      function handleLoading(img, src, layout, placeholder, onLoadingComplete) {
-        if (!img) {
-          return;
-        }
+      function handleLoading(
+        imgRef,
+        src,
+        layout,
+        placeholder,
+        onLoadingCompleteRef
+      ) {
         var handleLoad = function() {
+          var img = imgRef.current;
+          if (!img) {
+            return;
+          }
           if (img.src !== emptyDataURL) {
             var p = "decode" in img ? img.decode() : Promise.resolve();
             p.catch(function() {}).then(function() {
+              if (!imgRef.current) {
+                return;
+              }
               if (placeholder === "blur") {
                 img.style.filter = "";
                 img.style.backgroundSize = "";
                 img.style.backgroundImage = "";
                 img.style.backgroundPosition = "";
               }
-              loadedImageURLs.add(src);
-              if (onLoadingComplete) {
+              if (onLoadingCompleteRef.current) {
                 var naturalWidth = img.naturalWidth,
                   naturalHeight = img.naturalHeight;
                 // Pass back read-only primitive values but not the
                 // underlying DOM element because it could be misused.
-                onLoadingComplete({
+                onLoadingCompleteRef.current({
                   naturalWidth: naturalWidth,
                   naturalHeight: naturalHeight
                 });
@@ -429,13 +461,15 @@
             });
           }
         };
-        if (img.complete) {
-          // If the real image fails to load, this will still remove the placeholder.
-          // This is the desired behavior for now, and will be revisited when error
-          // handling is worked on for the image component itself.
-          handleLoad();
-        } else {
-          img.onload = handleLoad;
+        if (imgRef.current) {
+          if (imgRef.current.complete) {
+            // If the real image fails to load, this will still remove the placeholder.
+            // This is the desired behavior for now, and will be revisited when error
+            // handling is worked on for the image component itself.
+            handleLoad();
+          } else {
+            imgRef.current.onload = handleLoad;
+          }
         }
       }
       function Image(_param) {
@@ -478,6 +512,8 @@
             "placeholder",
             "blurDataURL"
           ]);
+        var ref4;
+        var imgRef = (0, _react).useRef(null);
         var rest = all;
         var layout = sizes ? "responsive" : "intrinsic";
         if ("layout" in rest) {
@@ -521,7 +557,12 @@
           unoptimized = true;
           isLazy = false;
         }
-        if (true && loadedImageURLs.has(src)) {
+        if (
+          true &&
+          ((ref4 = imgRef.current) === null || ref4 === void 0
+            ? void 0
+            : ref4.complete)
+        ) {
           isLazy = false;
         }
         if (false) {
@@ -534,7 +575,7 @@
             }),
             2
           ),
-          setRef = ref3[0],
+          setIntersection = ref3[0],
           isIntersected = ref3[1];
         var isVisible = !isLazy || isIntersected;
         var wrapperStyle = {
@@ -667,6 +708,32 @@
           _defineProperty(_obj, imageSrcSetPropName, imgAttributes.srcSet),
           _defineProperty(_obj, imageSizesPropName, imgAttributes.sizes),
           _obj);
+        var useLayoutEffect = false ? 0 : _react.default.useLayoutEffect;
+        var onLoadingCompleteRef = (0, _react).useRef(onLoadingComplete);
+        (0, _react).useEffect(
+          function() {
+            onLoadingCompleteRef.current = onLoadingComplete;
+          },
+          [onLoadingComplete]
+        );
+        useLayoutEffect(
+          function() {
+            setIntersection(imgRef.current);
+          },
+          [setIntersection]
+        );
+        (0, _react).useEffect(
+          function() {
+            handleLoading(
+              imgRef,
+              srcString,
+              layout,
+              placeholder,
+              onLoadingCompleteRef
+            );
+          },
+          [srcString, layout, placeholder, isVisible]
+        );
         return /*#__PURE__*/ _react.default.createElement(
           "span",
           {
@@ -704,16 +771,7 @@
               decoding: "async",
               "data-nimg": layout,
               className: className,
-              ref: function(img) {
-                setRef(img);
-                handleLoading(
-                  img,
-                  srcString,
-                  layout,
-                  placeholder,
-                  onLoadingComplete
-                );
-              },
+              ref: imgRef,
               style: _objectSpread({}, imgStyle, blurStyle)
             })
           ),
Commit: e8c3214

@kodiakhq kodiakhq bot merged commit c879fce into canary Jan 20, 2022
@kodiakhq kodiakhq bot deleted the fix-infinite-on-loading-complete branch January 20, 2022 15:29
kodiakhq bot pushed a commit that referenced this pull request Jan 28, 2022
In PR #26968, we added Set of loaded images that was removed in #33474 erroneously.

We still need to track loaded images since we can't rely on `img.complete`, especially if the parent uses `react-virtualized`.

Tested on https://nextjs.org/showcase
natew pushed a commit to natew/next.js that referenced this pull request Feb 16, 2022
The image prop `onLoadingComplete()` was unexpectedly called multiple times because it uses a [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs).

This could lead to an infinite loop if `onLoadingComplete()` calls `setState()` as demonstrated in the updated test.

The solution is to handle refs with `useRef()` and `useEffect` so `onLoadingComplete()` is called at most once per component instance.

- Fixes vercel#33463
natew pushed a commit to natew/next.js that referenced this pull request Feb 16, 2022
In PR vercel#26968, we added Set of loaded images that was removed in vercel#33474 erroneously.

We still need to track loaded images since we can't rely on `img.complete`, especially if the parent uses `react-virtualized`.

Tested on https://nextjs.org/showcase
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 20, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

onLoadingComplete is being called several times when parent rerenders
3 participants