I've created a custom Next JS carousel that tracks the current slide index and displays an image or video accordingly. However, it appears that because the carousel is set to autoplay and each slide is removed and readded every 6 seconds, the page downloads duplicate copies of the same media when they cycle back around. Is this the correct approach?
The crux of the issue lies here
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
It continuously removes and adds content for each slide. Could this be wasting resources by constantly downloading them? Is there a more efficient way to handle this?
import React from 'react'
//Importing data for the slides
import { slides } from './data/slides'
import VideoSlide from './VideoSlide'
import ImageSlide from './ImageSlide'
let slideTimer = null
class Carousel extends React.Component {
constructor(props) {
super(props)
this.state = {
currentImageIndex: 0, //Index of slide in /data/slides
slideTime: 6, //Duration of each slide in seconds
}
this.setMyInterval = this.setMyInterval.bind(this)
}
//Initial setup when component mounts
componentDidMount() {
this.setMyInterval()
}
changeSlide(current) {
/*Avoid running if selecting same slide number*/
if (current != this.state.currentImageIndex) {
this.setState({ currentImageIndex: current }) //Change to selected slide
clearTimeout(slideTimer) //Reset timer
this.setMyInterval() //Rebuild the countdown
}
}
setMyInterval() {
slideTimer = setInterval(() => {
const lastIndex = slides.length - 1
const { currentImageIndex } = this.state
const shouldResetIndex = currentImageIndex === lastIndex
const index = shouldResetIndex ? 0 : currentImageIndex + 1
this.setState({
currentImageIndex: index,
})
}, this.state.slideTime * 1000)
}
componentWillUnmount() {
clearInterval(slideTimer)
}
render() {
return (
<>
<div className="backgroundSlide">
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
<VideoSlide url={slides[0].video} />
{slides[this.state.currentImageIndex].image && (
<ImageSlide
url={slides[this.state.currentImageIndex].image}
timer={this.state.slideTime}
/>
)}
</div>
)}
</>
))}
</div>
</>
)
}
}
export default Carousel