twobin / react-lazyload

Lazy load your component, image or anything matters the performance.
MIT License
5.85k stars 487 forks source link

The first component loads more than once. #411

Open RezaGhx opened 1 year ago

RezaGhx commented 1 year ago

the first component which has been loaded on the first view, loads again after scrolling.

the image attached on the task, describes the problem. after the page mounts, the first avatar, which marked with a red one, loads first of all but when we scroll down the page, it loads again.

but the other avatars like the second, and the third specified on the attachment, loads only on their visible condition and it's a correct behavior.

this issue causes at least 2x requests on the server and seems harmful on the project performance.

the image attached is from the Google Chrome devTools, where you can see the request called twice; however the first avatar's request called about 4 or 5 times according to our Mozilla Firefox observations.

here is a snippet of simple usage:

snippet

`import { Image } from 'antd'; import LazyLoad from 'react-lazyload';

const Avatar = ({ src }) => { return (

{'lorem'}

); };`

also I found a relatable issue on the package issues but unfortunately it has been closed without any answers or comments.

203

react_lazyload_issue

kyoungholee commented 3 months ago
  1. Remove the timestamp

import { Image } from 'antd'; import LazyLoad from 'react-lazyload';

const Avatar = ({ src }) => { return (

<LazyLoad>
  <Image height={85} width={85} src={src ? src : '/img/user.png'} />
</LazyLoad>

); };

export default Avatar;

  1. Fixed a timestamp

import React, { useState, useEffect } from 'react'; import { Image } from 'antd'; import LazyLoad from 'react-lazyload';

const Avatar = ({ src }) => { const [imageSrc, setImageSrc] = useState(src ? ${src}?${new Date().getTime()} : '/img/user.png');

useEffect(() => { if (src) { setImageSrc(${src}?${new Date().getTime()}); } else { setImageSrc('/img/user.png'); } }, [src]);

return (

<LazyLoad>
  <Image height={85} width={85} src={imageSrc} />
</LazyLoad>

); };

export default Avatar;

  1. Component Optimization

import React, { useState, useEffect } from 'react'; import { Image } from 'antd'; import LazyLoad from 'react-lazyload';

const Avatar = React.memo(({ src }) => { const [imageSrc, setImageSrc] = useState(src ? ${src}?${new Date().getTime()} : '/img/user.png');

useEffect(() => { if (src) { setImageSrc(${src}?${new Date().getTime()}); } else { setImageSrc('/img/user.png'); } }, [src]);

return (

<LazyLoad>
  <Image height={85} width={85} src={imageSrc} />
</LazyLoad>

); });

export default Avatar;