Q: SetInterval Showing default State value every time in React Js CurrentIndex is showing 0 every time I want to run it to custom duration or dynamic array length
    Const [currentIndex, setCurrentIndex] = useState(1);

    useEffect(() => {
    setInterval(() => {
      setCurrentIndex(5);
      if (currentIndex >= 5) {
        setCurrentIndex(0);
      }
      console.log('Current Index', currentIndex);
    }, 3000);
  }, []);


A: React state is async so it take some time delay for update. so use separate  useEffect hook for listen index
Const[currentIndex, setCurrentIndex] = useState(1);

useEffect(() => {
  if (currentIndex >= 5) {
    setCurrentIndex(0);
  }
  console.log('Current Index', currentIndex);
}, [currentIndex])

useEffect(() => {
  setInterval(() => {
    setCurrentIndex(5);
  }, 3000);
}, []);


A: You can do it like that


  var [currentIndex, setCurrentIndex] = useState(1);

  useEffect(() => {
    setInterval(() => {
      setCurrentIndex(5);
      if (currentIndex >= 5) {
        setCurrentIndex(0);
      }
      console.log("Current Index", currentIndex);
    }, 3000);
  }, [currentIndex]);


