Previous image stays while the next is loading

Viewed 144

A quick demo: Codesandbox link

Notice that when the image is switched, text related to the next image appears right away, but as the next image loads, the previous one stays there until the next one hasn't fully loaded.

Initially, the user sees:

Text 1
[             ]
[    Image1   ]
[             ]

On switching, the next image takes some time to load, so the user sees

Text 2
[             ]
[    Image1   ]
[             ]

and then,

Text 2
[             ]
[    Image2   ]
[             ]

Ideally, I'd like to clear the previous image while the next one is loading. Is there a way to do this? That is, while the next image is loading, the user should seee

Text 2
[             ]
[             ]
[             ]

Obviously, this only happens the first time an image is loaded. After an image is fetched (and I guess stored in session cache or something), there is no delay when the images are switched.

3 Answers

You can take another state variable

  const [show, setShow] = useState(false);

Then Change your handleImageSwitch function to this

const handleImageSwitch = () => {
    setShow(false);
    item === 0 ? setItem(1) : setItem(0);
  };

Change Your Image Tag to this

<img
  onLoad={() => setShow(true)}
  style={{
    maxWidth: "200px",
    display: show ? "block" : "none",
    margin: "0 auto"
  }}
  src={images[item].url}
  alt=""
/>

Check my Sandbox: https://codesandbox.io/s/affectionate-goldwasser-fbr3c?file=/src/App.js

It takes time to fetch image. you can put images in state (useState([]) and fetch images in useEffect hook or a function and use a loading state. before fetching image, set loading to true. When loading is true, you can show blank or anything in place of image. This way you only have to fetch image once.

Related