I want to ask regarding my setInterval function. I wanted to do something like a carousel auto scroll for my Quotes component.
Problem: The setInterval incremented my currQuote state from 0 to 1 and then stops at 1 and did not set back to 0 as coded in the else statement.
SOLVED: Thank you guys. This was a very silly mistake. I didnt add the dependencies for the useEffect. No wonder it just run once XD
const Quote = () => {
const [currQuote, setCurrQuote] = useState(0);
const timerQuote = useRef();
useEffect(() => {
timerQuote.current = setInterval(() => {
if (currQuote < quoteList.length - 1) {
setCurrQuote(currQuote + 1);
} else {
setCurrQuote(0);
}
// console.log(currQuote);
}, 2000);
// dispose when unmount
return () => {
clearInterval(timerQuote.current);
};
}, []);
useEffect(() => {
console.log(currQuote);
}, [currQuote]);
return(.......)