soyjavierdev
soyjavierdev

Reputation: 31

How to change image every 4 seconds with React hooks?

Sorry if I don't ask well, it's my first time.

I want to change the image every 4 seconds of this link: https://picsum.photos/200 that every time the page or the status is refreshed, the image is changed.

I have tried to do it with a second state that is a counter with setInterval and use useEffect in the update phase of the [counter] but I am stuck. This is my code:

import { useEffect, useState } from "react";

import "./styles.css";

export default function App() {

  const [photo,setPhoto] = useState('https://picsum.photos/200')

  useEffect(()=>{
    setPhoto(photo)
  },[])

  
  return (
    <div className="App">
      <h1>Photo:</h1>
      <img src={photo}></img>
    </div>
  );
}

Upvotes: 1

Views: 898

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196286

You need to use something that changes the url each time you want to change the image.

A common approach, is to use a timestamp and append it at the end of the image src attribute, tricking the browser into thinking it is different image (and thus not using the cached version).

You can use setInterval to repeat the process every 4 seconds.

export default function App() {
  const photo = "https://picsum.photos/200";
  const [timestamp, setTimestamp] = useState(Date.now());

  useEffect(() => {
    const timer = setInterval(() => {
      setTimestamp(Date.now());
    }, 4000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="App">
      <h1>Photo:</h1>
      <img src={`${photo}?_=${timestamp}`} alt="random"></img>
    </div>
  );
}

Demo at https://codesandbox.io/s/romantic-browser-17gw1z

Upvotes: 1

Wraithy
Wraithy

Reputation: 2056

Just setup interval to change url way you want.. in my demo it will just increment

import { useEffect, useRef, useState } from "react";

import "./styles.css";

export default function App() {
  const [photo, setPhoto] = useState("https://picsum.photos/200");
  const i = useRef(200);
  useEffect(() => {
    const handle = setInterval(() => {
      i.current += 1; //here should be some more soffisticated url creation
      setPhoto(`https://picsum.photos/${i.current}`);
    }, 4000);
    return () => clearInterval(handle);
  }, []);

  return (
    <div className="App">
      <h1>Photo:</h1>
      <img src={photo}></img>
    </div>
  );
}

working demo: https://codesandbox.io/embed/fervent-dream-tq0xng

Upvotes: 0

Marat
Marat

Reputation: 94

I had the same problem recently. Try to replace your useEffect with this one:

useEffect(()=>{
    setPhoto(photo)
},[photo])

useEffect hook take a second params called dependency array, where this dependency array is what matter for the inner callback(inisde useEffect) to access the latest values you want.

Upvotes: 0

Related Questions