You see I am using ReactJs and Tailwind for a small personal project. I have a list of 6 images, that I am then rendering like so:
import React from "react";
import Images from "../images";
export default function PictureHeader() {
const [pictureIndex, setPictureIndex] = React.useState(0);
const animationRef = React.useRef<HTMLDivElement>(null);
const node = animationRef.current;
const pictures: string[] = Images.pictures;
const removeAnimation = () => {
node?.className.includes("fade-out")
? node.className.replace("fade-out", "fade-in")
: node?.className.concat(" fade-in");
}
React.useEffect(() => {
removeAnimation();
setInterval(() => {
nextPicture();
}, 2500);
});
const nextPicture = () => {
const newIndex = (pictureIndex 1) % pictures.length;
setPictureIndex(newIndex);
node?.className.replace("fade-in", "fade-out");
}
console.log(pictureIndex);
return (
<div className="padding-10 top-0 inset-x-0 place-content-center">
<div className="w-4/5 select-none relative rounded-lg">
<div ref={animationRef} className="absolute content-left aspect-w-16 aspect-h-9 cover z-0">
<img src={pictures[pictureIndex]} />
</div>
<div className="absolute inset-x-0 bottom-0 justify-items-center z-10">
<h1 className="6xl font-dancing">
Sierra and Adam
</h1>
<h2 className="4xl font-dancing">
Save the date for a match of the Millenia!
</h2>
</div>
</div>
</div>
);
}
When I run this page, I find that after a few re-renders the pictures shows up in a strange list: 0,0,1,1,0,0,1,1,2,2,0,0,1,1,2,2,3,3... and so on until the webpage could probably induce seizures. (See the picture below for what I mean.)
Am I missing something with this? Any help would be appreciated!
CodePudding user response:
It turns out I am stupid and forgot that you must clear the interval:
React.useEffect(() => {
removeAnimation();
const interval = setInterval(() => {
nextPicture();
}, 2500);
return () => clearInterval(interval);
});
I assume this is because this is just adding more and more interval s to change the state as it runs so eventually you are just exploding through the queue.