I am using React to load and render images as items of a carousel component. I am using the useState hook to set the currently active carousel item, and when a user clicks the next or back arrow, I use the set function of the useState hook to update the active item. I then use CSS animations to animate the rotation of the carousel items.
However, with this implementation, the component re-requests the image asset every time the carousel's active item changes, causing a flash on the image.
Here is how it's currently set up to handle animating the carousel.
// Component
const Carousel = ({ data }: Props) => {
const [activeItem, setActiveItem] = useState(0)
const back = () => {
const newActive = activeItem - 1
setActiveItem(newActive < 0 ? slice.items.length - 1 : newActive)
}
const next = () => {
const newActive = activeItem + 1
setActiveItem(newActive % slice.items.length)
}
return (
<section>
<div className="carousel-container">
<button onClick={back}>Back</button>
<div className="carousel">
items.forEach((item, i) => {
let itemClass = "slide"
if (i === activeItem-1) itemClass += " prev"
else if (i === activeItem) itemClass += " active"
else if (i === activeItem+1) itemClass += " next"
else itemClass += " hidden"
return <CarouselItem item={item} className={itemClass} />
})
</div>
<button onClick={next}>Next</button>
</div>
</section>
)
}
// SCSS
.carousel {
.item {
transition: transform 0.4s cubic-bezier(0.28, 0.11, 0.3, 1.01), box-shadow 0.4s cubic-bezier(0.28, 0.11, 0.3, 1.01);
&.prev {
z-index: 0;
transform: translate3d(-35%, 0, -30px);
}
&.active {
z-index: 1;
transform: translate3d(0%, 0, 0px);
}
&.next {
z-index: 0;
transform: translate3d(35%, 0, -30px);
}
&.hidden {
z-index: -1;
transform: translate3d(0, 0, -50px);
}
}
}
How can I get this component to update it's state (i.e. animate the rotation of the carousel) without re-requesting the already loaded images?