'React native animated object does not move

I am new to React Native animated, and I am trying to incorporate it into my app. I currently have an object that appears to fall from the middle to the bottom of the screen, using frequent state updates like this:

const [objHeight, setObjHeight] = useState((Dimensions.get("screen").height)/2)

  useEffect(()=>{
    if(objHeight > 0){
      timerId = setInterval(()=>{
          setObjHeight(objHeight => objHeight - 3)
       }, 30) //30ms

    return ()=>{
      clearInterval(timerId)
      }

  },[objHeight])

//then the object looks like:

    <View 
        style = {[{
            position: "absolute",
            backgroundColor: 'blue',
            width: 50,
            height: 60,
            bottom: objHeight,
        }]}>
    </View>

I understand that this is an inefficient way to do animations on react, and that by using react animated we can make animate this on the UI thread instead. I have tried to replicate the above using react native animated.

const objHeight = new Animated.Value(screenHeight/2)

Animated.loop(
  Animated.timing(objHeight, {
    toValue: objHeight>0 ? objHeight - gravity : null,
    duration: 3000,
    useNativeDriver: true
  }),
  {iterations: 1000}
).start()

<Animated.View 
   style = {[{
      backgroundColor: 'blue',
      width: 50,
      height: 60,
      bottom: 200,
      transform:[{translateY: objHeight}]
    }]}>
</Animated.View>

However, the object does not move/animate. It just stays at the same height. What am I doing wrong? I find the documentation on react native animated is not particularly helpful.

Thank you



Solution 1:[1]

Snack Link

First create an Animated.Value with some initial value:

const bottomAnim = useRef(new Animated.Value(Dimensions.get('screen').height / 2)).current;

Then on component mount start the animation:

useEffect(() => {
    Animated.timing(bottomAnim, {
      toValue: 0,
      duration: 3000,
      useNativeDriver: true,
    }).start();
  }, []);

Finally, bind the animated value to the component:

return (
    <Animated.View
      style={[
        {
          position: 'absolute',
          backgroundColor: 'blue',
          width: 50,
          height: 60,
          bottom: bottomAnim,
        },
      ]}/>
  );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tayyab Mazhar