I want to loop over an array of 3 months ["1", "2", "3"] and show the current month every 2 seconds. I tried using useEffet, useState and setInterval to build a cycle but i get an unwanted behavior.
Here is a sandbox i made : https://codesandbox.io/s/autumn-voice-y6kdpb?file=/src/App.js
import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const months = ["1", "2", "3"];
let count = 0;
const [month, setMonth] = useState(months[count]);
useEffect(() => {
function cycleArray() {
setMonth(months[count]);
// increment our counter
count++;
// reset counter if we reach end of array
}
if (count === months.length) {
count = 0;
}
setInterval(cycleArray, 1000);
}, [count]);
return (
<div className="App">
<h1>Loop over months (next month every 1 second) </h1>
<h2>{month}</h2>
</div>
);
}
What am I doing wrong ?