'React native animation => new Animated.Value() with useState or not?

What is the best way to use Animated.Value () in react-native ?

With useState() or not ?

const [fadeAnim] = useState(new Animated.Value(0))

Or

const fadeAnim = new Animated.Value(0)

React-native doc: https://facebook.github.io/react-native/docs/animations

Thanks



Solution 1:[1]

I came across a dodgy UI bug where settings hook values would render in the view instantly and mess up the animations. I fixed this by putting putting the animation value in a useState hook like so:

Before:

const foo = new Animated.Value(1)

After:

  const [foo] = useState(new Animated.Value(1));

Solution 2:[2]

I've been using this recently:

const [fadeAnim] = useState(() => new Animated.Value(0));

and for set value the standard:

fadeAnim.setValue(0);

Also, you might want to look at useRef too, since it is what documentation recommend:

const fadeAnim = useRef(new Animated.Value(0)).current;
/* 
... 
*/
fadeAnim.setValue(0);

Solution 3:[3]

Use useRef() as recommended in https://reactnative.dev/docs/animated and https://reactnative.dev/docs/animations#animated-api.

const [fadeAnim] = useState(() => new Animated.Value(0)); is same but semantically "state" means getter and setter - without setter 'fadeAnim' will be same throughout the component's lifetime so no different than useRef(...).current

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 Maximillion Bartango
Solution 2
Solution 3 Rumen Neshev