OmerSch
OmerSch

Reputation: 125

Animation and state issue: using Animated.spring inside useEffect

I'm new to React-Native app development.
https://snack.expo.io/RjmfLhFYg
I'm trying to understand why the animation stops working if I un-comment line 11 setTest(false) in the linked expo snack.

Thank you!

Relevant code copy:

export default function App() {
  const element1 = useRef(new Animated.ValueXY()).current;
  const element2 = new Animated.ValueXY();
  const [test, setTest] = useState(true);

  useEffect(() => {
    // setTest(false);

    setTimeout(() => {
      Animated.spring(
        element2,
        {
          toValue: {x: -10, y: -100},
          useNativeDriver: true
        }
      ).start();
    }, 2000);
  }, []);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[styles.element, {backgroundColor: "blue"}, {
          transform: [
            {translateX: element2.x}, {translateY: element2.y}
          ]
        }]}>
      </Animated.View>
      <Animated.View
        style={[styles.element, {backgroundColor: "red"}, {
          transform: [{translateX: element1.x}, {translateY: element1.y}]
        }]}
        >
      </Animated.View>
    </View>
  );
}

Upvotes: 1

Views: 718

Answers (1)

Eduardo Tavarez
Eduardo Tavarez

Reputation: 480

useState docs

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

Remember that when you change the state of a component it causes a "re-render" so your element2 variable gets back to its initial value. To solve it use the "useRef" hook on the element2 variable just like you did with element1.

const element2 = useRef(new Animated.ValueXY()).current;

"useRef" hook will make the variable persistent through the component life cycle so it won't be affected if the component gets re-rendered

useRef docs

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Upvotes: 2

Related Questions