Hieu Nguyen — October 10, 2020
Unexpected behavior with React hydration
I've recently realized my server render pages has a problem. The offscreen lazyload image don't show up.
In case you don't know, offscreen images won't load until it shows up onscreen. It helps to reduce unecessery loading to improve performance.
As usual, I impletemented image lazy loading by (1) get all img elements, (2) move photo URL to
data-src, and remove
src. Then (3) observe whenever each of them scrolled onscreen, move the photo URL back to
src to load.
It works when React running on the client-side. But when render on the server-side, the images don't show up.
Turn out, it's a little different. As usual, the server will return a hydrated React page. Then the client will re-render the page again as a normal React page.
The problem was, the lazyload function executed twice as well. The first time,
src is a link, and set to
empty after assigning the link to
data-src. Then the second time,
src was empty, and that empty value is again, assigned to
data-src. And when users viewing the page, it will start to load an empty value.
I fixed this problem by checking if
src is not empty, before moving it to
In case you're looking for the code, here is a basic lazy loading with some favors (add loading class, check for offscreen images)
Share this post
I'm a developer, hobbyist photographer. Building Inverr — a NoCode Site Builder