3

To create a custom View with translateY I have to calculate the height of the container and content using onLayout. This worked perfectly, but today I've added an Accordion component which also animates. This happens to trigger the onLayout functions to render on every calculated frame, which makes my application very slow. I've tried adding the useCallback and the LayoutAnimation to fix this, but this both didn't seem to work.

Is there a way to trigger the onLayout only before and after the animation? I thought about adding a debounce to the onLayout, but hopefully, there is another solution.

export default memo(({ translateY }) => {
  const [containerHeight, setContainerHeight] = useState(0);
  const [contentHeight, setContentHeight] = useState(0);

  console.log('render', containerHeight, contentHeight);

  const onLayoutContainer = useCallback(event => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    const height = event.nativeEvent.layout.height;
    setContainerHeight(height);
  }, []);

  const onLayoutContent = useCallback(event => {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    const height = event.nativeEvent.layout.height;
    setContentHeight(height);
  }, []);

  return (
    <View onLayout={onLayoutContainer}>
        <Animated.View
          onLayout={onLayoutContent}
          style={{ transform: [{ translateY }] }}
        >
            <Accordion />
            <Accordion />
            <Accordion />
            <Accordion />
            <Accordion />
            <Accordion />
        </Animated.View>
    </View>
  );
});
aminography
  • 21,986
  • 13
  • 70
  • 74
ronnyrr
  • 1,481
  • 3
  • 26
  • 45

0 Answers0