react-native-reanimated-carousel icon indicating copy to clipboard operation
react-native-reanimated-carousel copied to clipboard

Performance Lag in Carousel Animations on Real Android Devices Compared to Simulator

Open defild9 opened this issue 2 years ago • 21 comments

Describe the bug On a real Android device, animations in the CarouselListItem component are noticeably slower compared to the Android simulator. This issue manifests as lag during image scrolling, item transitions, and gesture handling. The performance difference is more pronounced on real devices.

To Reproduce Steps to reproduce the behavior:

  1. Implement the following CarouselListItem component:

    const CarouselListItem = ({
      item,
      shareHandler,
      addToWishlistHandler,
      removeFromWishlistHandler,
      stared,
    }: CarouselItem) => {
      const [currentImageIndex, setCurrentImageIndex] = React.useState(0);
    
      const baseOptions = {
        vertical: false,
        width: PAGE_WIDTH * 0.9,
        height: 232,
      } as const;
    
      const images = item?.lot?.image_urls || [];
      const isSold = item.lot.is_sold;
    
      return images.length > 0 ? (
        <CarouselContainer>
          <Carousel
            {...baseOptions}
            data={images}
            windowSize={3}
            scrollAnimationDuration={200}
            onSnapToItem={(index) => setCurrentImageIndex(index)}
            pagingEnabled={true}
            onProgressChange={(_, absoluteProgress) => {
              setCurrentImageIndex(Math.round(absoluteProgress));
            }}
            panGestureHandlerProps={{
              activeOffsetX: [-10, 10],
            }}
            renderItem={({ item }) => (
              <Flexbox>
                <ImageBackground
                  style={{ flex: 1 }}
                  imageStyle={{ borderTopLeftRadius: 16, borderTopRightRadius: 16 }}
                  source={{ uri: item }}
                >
                  <Flexbox justifyContent={'space-between'} borderRadius={16} height={232}>
                    <Flexbox flexDirection={'column'}>
                      <TouchableOpacity
                        onPress={shareHandler}
                        style={{
                          padding: 15,
                          backgroundColor: '#0C0C0C80',
                          borderTopLeftRadius: 16,
                          borderBottomRightRadius: 8,
                        }}
                      >
                        <ShareIcon />
                      </TouchableOpacity>
                    </Flexbox>
                    <Flexbox flexDirection={'column'}>
                      <TouchableOpacity
                        disabled={isSold}
                        onPress={
                          stared
                            ? removeFromWishlistHandler
                            : addToWishlistHandler
                            ? addToWishlistHandler
                            : () => {}
                        }
                        style={{
                          padding: 15,
                          backgroundColor: '#0C0C0C80',
                          borderTopRightRadius: 16,
                          borderBottomLeftRadius: 8,
                        }}
                      >
                        {stared ? (
                          <StarFilledIcon color={'#fff'} />
                        ) : (
                          <StarIcon color={isSold ? '#a0a0a0' : '#fff'} />
                        )}
                      </TouchableOpacity>
                    </Flexbox>
                  </Flexbox>
                </ImageBackground>
              </Flexbox>
            )}
          />
    
          <Dots
            passiveDotHeight={8}
            passiveDotWidth={8}
            activeDotWidth={12}
            activeDotHeight={8}
            length={images.length}
            active={currentImageIndex}
            activeColor="#1B6BC8"
            passiveColor="#E8EBEF"
          />
        </CarouselContainer>
      ) : (
        <TouchableWithoutFeedback>
          <Flexbox>
            <ImageBackground
              style={{ flex: 1 }}
              imageStyle={{ borderTopLeftRadius: 16, borderTopRightRadius: 16 }}
              source={{ uri: item.lot.image_urls[0] ?? item.lot.thumb }}
            >
              <Flexbox justifyContent={'space-between'} borderRadius={16} height={232}>
                <Flexbox flexDirection={'column'}>
                  <TouchableOpacity
                    onPress={shareHandler}
                    style={{
                      padding: 15,
                      backgroundColor: '#0C0C0C80',
                      borderTopLeftRadius: 16,
                      borderBottomRightRadius: 8,
                    }}
                  >
                    <ShareIcon />
                  </TouchableOpacity>
                </Flexbox>
                <Flexbox flexDirection={'column'}>
                  <TouchableOpacity
                    disabled={isSold}
                    onPress={
                      stared
                        ? removeFromWishlistHandler
                        : addToWishlistHandler
                        ? addToWishlistHandler
                        : () => {}
                    }
                    style={{
                      padding: 15,
                      backgroundColor: '#0C0C0C80',
                      borderTopRightRadius: 16,
                      borderBottomLeftRadius: 8,
                    }}
                  >
                    {stared ? (
                      <StarFilledIcon color={'#fff'} />
                    ) : (
                      <StarIcon color={isSold ? '#a0a0a0' : '#fff'} />
                    )}
                  </TouchableOpacity>
                </Flexbox>
              </Flexbox>
            </ImageBackground>
          </Flexbox>
        </TouchableWithoutFeedback>
      );
    };
    
    export default CarouselListItem;
    
  2. Run the app on both a real Android device and an Android simulator.

  3. Scroll through the images in the carousel on both platforms.

  4. Observe the difference in animation performance.

Expected behavior Animations should be smooth and responsive on both real Android devices and Android simulators.

Screenshots N/A

Versions (please complete the following information):

  • react: v18.2.0
  • react-native: v0.72.410
  • react-native-reanimated: v3.14.0
  • react-native-reanimated-carousel: v3.5.1
  • react-native-gesture-handler: v2.17.1

Smartphone (please complete the following information):

  • Device: Samsung Galaxy S9
  • OS: Android 10
  • Browser: N/A
  • Version: N/A

Additional context The issue might be related to the processing power differences between simulators and real devices, or it could be due to the configuration of scrollAnimationDuration, panGestureHandlerProps, or the complexity of the components within the carousel. Testing on multiple devices and optimizing gesture handling and animations may help resolve this.

defild9 avatar Aug 29 '24 21:08 defild9

Hey there, @defild9! I'm here to help you with any bugs, questions, or contributions you have in mind. Let's squash those bugs together! 🤖

To address the performance lag in the CarouselListItem component's animations on real Android devices, you can try the following steps:

  1. Update the react-native-reanimated-carousel Package: Ensure you are using the latest version of the react-native-reanimated-carousel package. The latest patch reduces the amount of work done when rendering data, which should help improve performance [1].

  2. Optimize Animation Style: Use the interpolate and Extrapolate functions from react-native-reanimated to ensure smoother transitions and less computational overhead. Here is an example of how you can define a custom animation style:

    import { Extrapolate, interpolate } from "react-native-reanimated";
    import Carousel, { TAnimationStyle } from "react-native-reanimated-carousel";
    
    const animationStyle: TAnimationStyle = (value: number) => {
      "worklet";
    
      const itemOffsetInput = new Array(sideItemCount * 2 + 1)
        .fill(null)
        .map((_, index) => index - sideItemCount);
    
      const itemOffset = interpolate(
        value,
        itemOffsetInput,
        itemOffsetInput.map((item) => {
          if (item < 0) {
            return (-itemSize + sideItemWidth) * Math.abs(item);
          } else if (item > 0) {
            return (itemSize - sideItemWidth) * (Math.abs(item) - 1);
          }
          return 0;
        }) as number[],
      );
    
      const translate = interpolate(value, [-1, 0, 1], [-itemSize, 0, itemSize]) + centerOffset - itemOffset;
    
      const width = interpolate(value, [-1, 0, 1], [sideItemWidth, itemSize, sideItemWidth], Extrapolate.CLAMP);
    
      return {
        transform: [
          {
            translateX: translate,
          },
        ],
        width,
        overflow: "hidden",
      };
    };
    
  3. Adjust windowSize and scrollAnimationDuration Props: The windowSize prop can be used to control how many items are rendered around the current item. Reducing this number can improve performance. The default value is 0, which means all items will respond to pan gesture events [2]. You can try setting it to a smaller value, such as 3, as you have done in your example.

    The scrollAnimationDuration prop controls the duration of the scroll animation. The default value is 500 ms [2]. You can experiment with different values to find the optimal duration for smooth animations.

  4. Review Similar Issues: There are similar issues reported in the repository that might provide additional insights:

By following these steps, you should be able to mitigate the performance issues you're experiencing on real Android devices.

To continue talking to Dosu, mention @dosu.

dosubot[bot] avatar Aug 29 '24 21:08 dosubot[bot]

same issue

jun-jaehyuk-lee avatar Sep 27 '24 07:09 jun-jaehyuk-lee

same

HelgiMagic avatar Oct 04 '24 10:10 HelgiMagic

same behaviour

kanounzied avatar Feb 11 '25 18:02 kanounzied

Hey, I've released the v4. Could you try with the latest version and let me know what happened?

dohooo avatar Feb 11 '25 20:02 dohooo

@dohooo it still lagging. Here are two recordings of my carousel

https://www.mediafire.com/file/3cfsayeqaaqjkz4/VID_20250211_223152.mp4/file

https://www.mediafire.com/file/xmb82nlf020fn9m/VID_20250211_223300.mp4/file

this is my implementation code for it. In my case I am using custom animation


const carouselAnimationStyle = useCallback((value: number) => {
    'worklet';
    const top = interpolate(value, [-1, 0, 1], [40, 0, 40]);
    const scale = interpolate(value, [-1, 0, 1], [0.78, 0.86, 0.78]);
    const translateX = interpolate(
      value,
      [-1, 0, 1],
      [-windowWidth * 0.8, 0, windowWidth * 0.8]
    );
    return {
      top,
      transform: [{ translateX }, { scale }],
    };
  }, []);

<Carousel
          width={Dimensions.get('window').width}
          windowSize={3}
          height={imageHeight}
          loop={false}
          pagingEnabled
          snapEnabled
          mode="parallax"
          style={{
            marginLeft: -15,
            marginRight: -15,
            marginTop: -28,
            overflow: 'visible',
          }}
          panGestureHandlerProps={{
            activeOffsetX: [-10, 10],
          }}
          customAnimation={carouselAnimationStyle}
          data={data?.media}
          renderItem={({ item, index }: CarouselRenderItemInfo<PostActivity>) => {
            FastImage.preload([{ uri: item.image, priority: 'low' }]);
            return (
              <Pressable
                style={[carouselStyle.image, {
                  width: '100%',
                  alignItems: 'center',
                  shadowOffset: {
                    width: 0,
                    height: 35,
                  },
                  shadowColor: '#000',
                  shadowOpacity: 0.6,
                  shadowRadius: 30,
                  elevation: 30,
                }]}
                onPress={() => openFullScreenCarousel(index)}
              >
                <MediaLoader
                  source={index === videoIndex ? item.image : item.image_thumbnail}
                  thumbnail={item.image_thumbnail}
                  style={carouselStyle.image}
                  videoShouldPlay={index === videoIndex}
                />
              </Pressable>
            );
          }}
          showsVerticalScrollIndicator={false}
          defaultIndex={imageActiveIndex}
          onSnapToItem={(index) => setVideoIndex(index)}
        />

kanounzied avatar Feb 11 '25 21:02 kanounzied

any news ?

kanounzied avatar Feb 13 '25 15:02 kanounzied

same issue - laggy performance only on real devices IOS & Android (Iphone 14 pro max and pixel 5), windowSize doesn't help. Link for my issue - https://github.com/dohooo/react-native-reanimated-carousel/issues/785

bohdan-heiko-solid avatar Feb 17 '25 20:02 bohdan-heiko-solid

I replaced panGestureHandlerProps with the new configuration , the old one is stale and i think it didnt work when i updated to version 4. onConfigurePanGesture={(panGesture: PanGesture) => { panGesture.activeOffsetX([-10, 10]) }}

performance was improved a lot but still lags a bit when I scroll to the next image, there is a glitch if i pause scrolling midway to the next image.

kanounzied avatar Feb 18 '25 08:02 kanounzied

Maybe it will help someone: I had the same problem and solved it by disabling new arch in gradle.properties. My libs versions:

"react-native": "0.76.5", "react-native-reanimated": "latest", "react-native-reanimated-carousel": "4.0.2",

michalnatkanski avatar Jun 06 '25 06:06 michalnatkanski

same issue

sumittttpaul avatar Jun 30 '25 06:06 sumittttpaul

Yes, @michalnatkanski

I can confirm that carousel looks fine on old architecture, but has performance issues if new architecture enabled, especially on Android.

CC: @dohooo

oleksandr-dziuban avatar Jul 28 '25 11:07 oleksandr-dziuban

Can this lib be verified under new architecture? Seems like it's not really working fine with it

oleksandr-dziuban avatar Jul 28 '25 11:07 oleksandr-dziuban

any news

ilyasssan2 avatar Sep 08 '25 15:09 ilyasssan2

Hey, can you try this?

dohooo avatar Sep 23 '25 10:09 dohooo

现在发现在轮播切换的时候,会导致一些一直在横向滚动的公告出现卡顿

YueLiXing avatar Nov 04 '25 02:11 YueLiXing

Same issue. with latest beta version of this lib with expo 54.

Any help? @dohooo

Shasikhan avatar Jan 14 '26 09:01 Shasikhan

same issue

ymasiuk-alt avatar Feb 27 '26 00:02 ymasiuk-alt

we reworked our main carousels with ScrollView carousels... and it performs much better that this one. I think library has a bunch of performance issues never solved yet.

oleksandr-dziuban avatar Feb 27 '26 07:02 oleksandr-dziuban

Could you reproduce this with [email protected] in a minimal Expo project and share the exact Expo, React Native, Reanimated, and Worklets versions, device model, New Architecture and Hermes settings, and a React Native performance trace? Please keep renderItem minimal first, then add images or customAnimation so we can separate carousel cost from item-rendering cost.

We’re focusing active maintenance on v5. Please provide the requested current-v5 reproduction by July 29, 2026. If no supported v5 reproduction is available by then, we’ll close this report; a new issue can always be opened later with updated evidence.

dohooo avatar Jul 16 '26 21:07 dohooo