I am trying to set up an image carousel that loops through 3 images when you mouseover a div. I'm having trouble trying to figure out how to reset the loop after it reaches the third image. I need to reset the setInterval so it starts again and continuously loops through the images when you are hovering over the div. Then when you mouseout of the div, the loop needs to stop and reset to the initial state of 0. Here is the Code Sandbox:
CodePudding user response:
Your setCount
should use a condition to check to see if it should go back to the start:
setCount((prevCount) => prevCount === images.length - 1 ? 0 : prevCount 1);
This will do setCount(0)
if we're on the last image—otherwise, it will do setCount(prevCount 1)
.
CodePudding user response:
Anything involving timers/intervals is an excellent candidate for
As to why your code didn't work, a few things:
- You meant to say
if (count === 2) ...
, notcount === 3
. Even better would be to use the length of theimages
array instead of hardcoding it - Moreover, the value of
count
was stale inside of the closure, i.e. after you updated it usingsetCount
, the old value ofcount
was still captured inside ofupdateCount
. This is actually the reason to use functional state updates, which you did when you said e.g.setCount((prevCount) => prevCount 1)
- You would have needed to loop the count inside the interval, not clear the interval on mouse over. If you think through the logic of it carefully, this should hopefully be obvious
- In general in react, using a function local variable like
timer
is not going to do what you expect. Always use state and effects, and in rarer cases (not this one), some of the other hooks like refs