Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native: Keep animated values in state or as class property?

Is it better to keep the animated value (fadeAnim) as a property of the state or is it ok to make it into a class-property?

Example:

class ModalShade extends React.Component {     fadeAnim = new Animated.Value(0)      render() {         return (             <Animated.View                 cls="bg-black absolute-fill"                 style={{ opacity: this.fadeAnim }}             />         )     }      componentDidMount() {         Animated.spring(             this.fadeAnim, {                 toValue: 0.6,                 tension: 100,                 friction: 20             }         ).start();     } } 

Clarification: I know that state is used for react's reconciliation. React-native' Animated values bypass the usual render(), so the component updates even when there's not state-change.

I don't see any point in comparing an Animated.Value in my shouldComponentUpdate, that's why I moved it out of state.

like image 331
Fabian Zeindl Avatar asked Nov 05 '16 09:11

Fabian Zeindl


People also ask

How do you value Animated values React Native?

To get the current value of Animated. Value with React Native, we call addListener on the animated value object. to call spinValue. addListener with a callback to get the current value of the animated value from the value property.

How animations work in React Native?

The folks at React Native allow you as a developer to provide a property called useNativeDriver as a boolean value when you're constructing an animation object. When set to true, React Native, before starting the animation, serializes the whole animation state and what needs to be done in the future.

Which of the following is a correct React Native animation type?

React Native provides two complementary animation systems: Animated for granular and interactive control of specific values, and LayoutAnimation for animated global layout transactions.


1 Answers

It is better to follow official documentation and to use state property. There are two good reasons for that:

  1. You want to keep all things that have effect on a component render result in your state/props/context.
  2. React-Native Animated library has its own optimizationzs that allows to avoid setState calls and re-rendering on change of Animated components. This is a quote from official documentation

When the component mounts, the opacity is set to 0. Then, an easing animation is started on the fadeAnim animated value, which will update all of its dependent mappings (in this case, just the opacity) on each frame as the value animates to the final value of 1.

This is done in an optimized way that is faster than calling setState and re-rendering.

like image 134
Roman Osypov Avatar answered Oct 13 '22 18:10

Roman Osypov