Home > Software design >  Should I be using useEffect to animate on prop value change with React Native Reanimated?
Should I be using useEffect to animate on prop value change with React Native Reanimated?

Time:01-20

I need a view to animate in to place when the value of some props change using Reanimated in React Native

I've only been able to find animating on, for example, a user tap using an onPress function to change the value of useSharedValue values. But I can't seem to find how to animate when props change. So currently I'm using useEffect.

export const SomeComponent = ({
  top,
  left
}) => { 
  const animation = useSharedValue({
    top,
    left
  });

  useEffect(() => {
    animation.value = { top, left };
  }, [top, left]);

  const animationStyle = useAnimatedStyle(() => {
    return {
      top: withTiming(animation.value.top, {
      duration: 1000
      }),
      left: withTiming(animation.value.left, {
      duration: 1000
      })
    };
  });
}

In the above code the props can change value, should I be triggering the animation with useEffect like I am currently? Or is there a better way to do it using just Reanimated.

CodePudding user response:

Interesting. This works? I haven't seen it done this way.

Yes, useEffect is a good way to trigger animations. Usually I would do it like this:

const duration = 1000;

export const SomeComponent = ({
  top: topProp,
  left: leftProp
}) => { 
  const top = useSharedValue(topProp);
  const left = useSharedValue(leftProp);

  useEffect(() => {
    top.value = withTiming(topProp, { duration });
    left.value = withTiming(leftProp, { duration });
  }, [topProp, leftProp]);

  const animationStyle = useAnimatedStyle(() => ({
    top: top.value,
    left: left.value,
  }));

  return <Animated.View style={animationStyle}>
    //...
}
  1. The values are split up so that they're primitives. I don't know if this affects performance - I've never used an object as a shared value before.
  2. The styles come straight from the shared values.
  3. The useEffect waits for props to change and then runs the animations.

I've never tried running the animations within the styles - it seems like it shouldn't work to me, but I could be wrong!

  • Related