javascriptreact-native

useAnimatedValue is not a function


I'm working on a small React Native project and I'm using the animated api for the first time. I'm attempting to make a small animated View that is pretty similar to the example given in their Docs. The issue I'm running into though is that when trying to run the project, I get this error:

TypeError: (0 , _index.useAnimatedValue) is not a function

I'm not sure what is happening, the component looks identical to what is being used in the example Docs

Here is the component:

import { Animated, useAnimatedValue } from "react-native";


const CookingView = (props) => {
  
  const cookAnim = useAnimatedValue(0);

  useEffect(() => {
    Animated.timing(cookAnim, {
      toValue: 1,
      duration: 10000,
      useNativeDriver: true,
    }).start();
  },[cookAnim]);

  return (
    <Animated.View 
      style={{
        ...props.style,
        opacity: cookAnim
      }}
    >
      { props.children }
    </Animated.View>
  );
}

export default CookingView;

Any ideas on to what is going on would be helpful. Thanks!


Solution

  • The issue is with the import statement. In React Native's Animated API, there's no useAnimatedValue hook.

    import React, { useEffect } from "react-native";
    import { Animated } from "react-native";
    
    const CookingView = (props) => {
      
      const cookAnim = new Animated.Value(0);
    
      useEffect(() => {
        Animated.timing(cookAnim, {
          toValue: 1,
          duration: 10000,
          useNativeDriver: true,
        }).start();
      }, [cookAnim]);
    
      return (
        <Animated.View 
          style={{
            ...props.style,
            opacity: cookAnim
          }}
        >
          { props.children }
        </Animated.View>
      );
    }
    
    export default CookingView;
    
    1. Remove useAnimatedValue from the import - it doesn't exist
    2. You need to import React and useEffect
    3. Use new Animated.Value(0): This is the correct way to create an animated value