I am a beginner using useEffect in React to update the index state of an array on an interval. I want the index to increase by 1 every five seconds, and when it reaches the end of the array loop back to 0.
I put an 'if' statement to check for this within my useEffect function, but it doesn't seem to be firing. When the array reaches the end, my console shows an error reading from an undefined index.
const [idx, setIdx] = useState(0);
useEffect(() => {
const interval = setInterval(() => setIdx((previousValue) => previousValue
1), 5000);
if(idx > testimonials.length-1) { setIdx(0)};
return () => {
clearInterval(interval);
};
}, []);
Can anyone see what I'm doing wrong?
CodePudding user response:
Use the remainder operator (%
):
const [idx, setIdx] = useState(0);
useEffect(() => {
const interval = setInterval(
() => setIdx(idx => (idx 1) % testimonials.length),
5000,
);
return () => clearInterval(interval);
}, []);
CodePudding user response:
You need to pass the idx value to the useEffect dependencies array.
import React from 'react';
const testimonials = [1, 2, 3, 4, 5, 6];
export default function App() {
const [idx, setIdx] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(
() => setIdx((previousValue) => previousValue 1),
1000
);
if (idx > testimonials.length - 1) {
setIdx(0);
}
return () => {
clearInterval(interval);
};
}, [idx]);
return (
<div>
<h1>{idx}</h1>
</div>
);
}
CodePudding user response:
you should use this statement
if(idx > testimonials.length-1) { setIdx(0)};
outside the useEffect and above the return which is returning the JSX.