Search code examples
javascriptreactjsreact-nativereduxreact-hooks

How to render an image every 5 seconds in React?


Every time you enter this url: https://picsum.photos/200, is shown a different image. I want my react component to render every 5 seconds a different image with this url, but I can't do it. This is my code:

import { useEffect, useState } from "react";

const VariableImage = () => {
  const imageUrl = "https://picsum.photos/200";

  const [image, setImage] = useState(imageUrl);

  useEffect(() => {
    setInterval(() => {
      const newImage = new Image();
      newImage.src = imageUrl;
      setImage(imageUrl);
    }, 5000);
  }, [imageUrl]);

  return (
    <>
      <img src={image} alt="scenery" height="200" width="200" />
    </>
  );
};

export default VariableImage;

An image is shown in first render but later don't change. If anyone could help me I would be very grateful. Thanks.


Solution

  • Add a dummy randomized query parameter to the external URL so as to force the browser to make a new request (and give you a new image).

    Doing new Image isn't helping you any here - you can leave that off entirely.

    const { useEffect, useState } = React;
    
    const imageUrl = "https://picsum.photos/200";
    const VariableImage = () => {
      const [src, setSrc] = useState(imageUrl);
      useEffect(() => {
        setInterval(() => {
          setSrc(imageUrl + '?forcerefresh=' + Math.random());
        }, 5000);
      }, []);
    
      return <img src={src} alt="scenery" height="200" width="200" />;
    };
    
    ReactDOM.createRoot(document.querySelector('.react')).render(<VariableImage />);
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <div class='react'></div>