I have a function that changes the value of a string variable to one from a list at set intervals. I figured setInterval would be ideal for this task but It behaves very strangely.
When the program loads, after the first interval delay, it will trigger the function twice, then a couple more times on the next interval. It progressively ramps up until it's triggering the function hundreds of times per interval.
From what I can understand, it's nothing to do with the function itself since I set up a manual trigger for the function and it works normally. (Whenever I call the function manually, it triggers once.)
const [dynString, setDynString] = useState(List[Index]);
setInterval(textTick, 5000);
function textTick(){
Index = Index + 1;
if(Index >= List.length){
Index = 0;
}
setDynString(List[Index]);
console.log('Current String:', Index);
}
return(
<div className='text-tick-object'>
<h1 onClick={textTick}>{dynString}</h1>
</div>
);
You should create intervals (side effects in general) inside useEffect() hooks. Any time the component re-renders (when you change the state inside the interval or after a click event) a new interval will start. You only need the interval once, at start
I would suggest something like this:
const list = ["a", "b", "c", "d"];
function MyComponent() {
const [index, setIndex] = useState(0);
const textTick = useCallback(() => {
setIndex((index) => {
let nextIndex = index + 1;
if (nextIndex >= list.length) {
nextIndex = 0;
}
console.log("Current String:", nextIndex);
return nextIndex;
});
}, []);
useEffect(() => {
const interval = setInterval(textTick, 5000);
return () => {
clearInterval(interval);
};
}, [textTick]);
return (
<div className="text-tick-object">
<h1 onClick={textTick}>{list[index]}</h1>
</div>
);
}
You can see this running in: https://stackblitz.com/edit/react-vn9hxx?file=src/App.js
(it's an external link, might not work in the future, the code is the same)