React Spring Carousel

Tips

While the library is easy to use, it's also easy to use it in the react way which can lead us to not use all the potential and the power of the library.

The following tips are a strong reccomendation on how to structure your Carousels but of course, if you prefer to, you can ignore them.

The first and most important thing when building a Carousel is the concept of state colocation. If you're not familiar with the concept, i suggest you to read this great article. In short, always colocate the state close to where it's relevant and, in case of our library, far away from the hook call. This affermation, though, it's not totally correct. The important thing to keep in mind is, do not update state while the carousel is animating.

I understand that this is very limitating, because many times our carousel needs to interact with other parts of our application and we need to update the UI while the carousel changes active slide, for example. So how to do it in the correct way? Well, here's where the concept of colocating state comes in our help.

Let's start with a very basic example; here we have a our carousel and we need to display the count of the active item.


  import { useTransitionCarousel } from 'react-spring-carousel'

  export function Component() {
    const [activeItem, setActiveItem] = useState(0)
    const {
      carouselFragment,
      useListenToCustomEvent,
      slideToPrevItem,
      slideToNextItem
    } = useSpringCarousel({
      withLoop: true,
      items: mockedItems.map((i) => ({
        id: i.id,
        renderItem: (
          <CarouselItem color={i.color}>
            {i.title}
          </CarouselItem>
        ),
      })),
    });

    useListenToCustomEvent((event) => {
      if (event.eventName === "onSlideStartChange") {
        setActiveItem(event.nextItem.id)
      } 
    });

    return (
      <div>
        <div>{activeItem + 1} / {mockedItems.length}</div>
        <div>
          {carouselFragment}
        </div>
      </div>
    );
  }

This is how many of us would do it, in a simple but common react way. On paper, and on modern devices, this is just fine. But imagine a real situation, where heavy stuff is updated