2

I've been trying to create dynamic image elemens which is going to lazy load when images shown on screen. Besides , image src and alt attribute that come from redux state , this state changes with dispatch action. But images just only load first render then won't load anymore.

This is the Lazy Image component that gives the capability to lazy load image via intersection observer api;

import React, { useState, useRef, useEffect } from 'react';

const LazyImage = ({ alt, src }) => {
    const [imageSrc, setImageSrc] = useState(null);
    const imgRef = useRef(null);

    useEffect(() => {
        setImageSrc(null);
    }, [src]);

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.intersectionRatio > 0) {
                        setImageSrc(src);
                        observer.unobserve(imgRef.current);
                    }
                });
            },
            {
                rootMargin: '0px',
                threshold: 0.1,
            }
        );
        observer.observe(imgRef.current);
        return () => {
            observer.unobserve(imgRef.current);
        };
    }, [src]);

    return <img ref={imgRef} src={imageSrc} alt={alt} />;
};

export default LazyImage;

This LazyImage component render on HOC with Array.map method; category array that changes when dispatch action successfully happen.

  <div className="slider">
   {category.map((el) => {
     return <LazyImage key={el.id} src={el.url} alt={el.name} />;
   })}
  </div>

This is the dummy db.json file which resides on imitated json-server and these category values fetching on server when dispatch action triggered.

{
    "categories:": {
        "Bakery": [
            {
                "id": "1",
                "name": "bread",
                "url": "https://via.placeholder.com/210/00FF00?text=1",
                "alt": "bread"
            },
            {
                "id": "2",
                "name": "croissant",
                "url": "https://via.placeholder.com/220/00FF00?text=2",
                "alt": "sdfalksdjflkasjdfk"
            },
            {
                "id": "3",
                "name": "birthday-cake",
                "url": "https://via.placeholder.com/230/00FF00?text=3",
                "alt": "sdfalksdjflkasjdfk"
            },
            {
                "id": "4",
                "name": "cheesecake",
                "url": "https://via.placeholder.com/240/00FF00?text=4",
                "alt": "sdfalksdjflkasjdfk"
            }
        ]
    }
}

Even if I add src props the dependency array on useEffect in LazyImage components that won't render out of initial render.

Due to lost last image element and create new one when category values change , images won't load correctly . But I don't know how to tackle this stattion as well.

0 Answers0