React Spring Carousel

Basic

Start using the carousel is simple!


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

  export function Component() {
    const { carouselFragment } = useSpringCarousel({
      items: [
        {
          id: 'item-1',
          renderItem: (
            <div>Item 1</div>
          )
        },
        {
          id: 'item-2',
          renderItem: (
            <div>Item 2</div>
          )
        }
      ]
    })

    return (
      <div>
        {carouselFragment}
      </div>
    );
  }

As you can see from the rendering code snippet, React Spring Carousel uses a different approach compared to what you would normally expect. Instead of rendering the component as you would normally do (<Component />), you just need to place the React Element that React Spring Carousel creates on the first mount (and eventually on the subsequent updates). As you could also see, the renderItem prop doesn't accept a function; instead, you need to pass a React Element as well.

Why did I took this approach? Mainly for performance reasons. The useSpringCarousel hook doesn't leverage on React State at all, so there're no rerenders; plus, since the whole rendering structure of the carousel isn't a component, the rendering tree is very light, and this gives us better animation results, since react won't execute any lifecycle for the carousel component; in most cases, rerenders will be faster and animations always smooth 🚄.