Rayberk
Rayberk

Reputation: 133

ReactJS change background color every X second in functional component

Hi i made a functional component and i have a interval in it.It changes the background image every 8 second there is total 5 photos it works fine for first 5 turn but after that it starts glitching

Here is the sandbox (interval is 3 seconds): https://codesandbox.io/s/infallible-darkness-8s2u4?file=/src/slider.js

Upvotes: 1

Views: 664

Answers (1)

Bart Krakowski
Bart Krakowski

Reputation: 1670

You should run this part of the code in the useEffect hook. Please remember to clean the interval:

useEffect(() => {
  const interval = setInterval(() => {
    if (state.img === 4) {
      setState((prev) => ({
        ...prev,
        img: 0
      }));
    } else {
      setState((prev) => ({
        ...prev,
        img: state.img + 1
      }));
    }
  }, 3000)
  return () => clearInterval(interval);
}, [state.img]);

Upvotes: 3

Related Questions