0

I would like to know which are the benefits of using React Lazy and Supense against what I am showing you below. First Example is using useState and Onload Prop, and second example is using React Lazy and Suspense.

const ImageComponent = ({ src }) => {
    const [load, setLoad] = useState(false);

    //handles load of the image
    const handleOnload = () => {
        setLoad(true);
    };

    return (
        <>
            {!load && <Spinner>}
            <img
                src={src}
                alt="Avatar"
                onLoad={handleOnload}
                style={{
                    height: '192px',
                    width: '50%',
                    display: load ? 'inline' : 'none',
                }}
            />
        </>
    );
};

VS this

        <Suspense
                fallback={
                    <Spinner style={{ width: '50%' }} />
                }
            >
            <ImageComponent src={listItem.download_url} />
        </Suspense>

ImageComponent.js

const ImageComponent = ({ src }) => {
    return (
        <img
            src={src}
            alt="Avatar"
            style={{
                height: '192px',
                width: '50%',
            }}
        />
    );
};

export default ImageComponent;
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Giler
  • 47
  • 5
  • I haven't really taken a good look at it yet, but I don't think your Suspense version would even work - the img tag wouldn't throw the relevant errors for the Suspense to kick in. – Zachary Haber Nov 10 '20 at 00:11
  • Or using the `loading="lazy"` attribute, or using an intersection observer on `img`, or ...? What are you actually trying to achieve, in case there's a great way to do that cleanly, but you simply didn't know about it and so didn't list it as options? – Mike 'Pomax' Kamermans Nov 10 '20 at 00:11
  • Well didnt know about that prop. I kind of new in React about few months learning. I was testing if React.lazy and Suspense increases the speed of DOM loading when you want to achieve an infinite scrolling. In this case retrieving the url of the images from an api and when you got to the bottom of the page, it start fetching more content. – Giler Nov 10 '20 at 02:01

0 Answers0