Search code examples
javascriptreactjsintervals

automatic content change react.js


I have a problem with the automatic content change. After 7 seconds it should change automatically by 1 (and so it works). The problem is that when the user clicks on the first card, after the carousel automatically goes to the second card, the interval, which is already running, completes its cycle and increases the index, causing the carousel to jump to the third card, not the the second etc.

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      const nextIndex = (activeIndex + 1) % expertise.length;
      setActiveIndex(nextIndex);
      ;
    }, 7000);
  
    return () => clearInterval(intervalRef.current);
  }, [activeIndex]);
  
  const handleCardClick = (index) => {
    setActiveIndex(index);
    clearInterval(intervalRef.current);
  };

I would like to see it work this way. If the content automatically changes to, for example, the fourth card, and the user then changes to the first, then after 7 seconds it should change to the second, and so on.


Solution

  • Simply use the functional form of setState so your captured activeIndex reference isn't stale.

    setActiveIndex(activeIndex => (activeIndex + 1) % expertise.length);