ReactJS change background color every X second in functional component

Viewed 375
1 Answers

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]);
Related