React Native - How to compare two Animated.Values in shouldComponentUpdate?

468 views Asked by At

I am optimizing my flatlist items (progressive images) and to avoid extending React.PureComponent I have decided to implement my own shouldComponentUpdate life-cycle method.

My progressive images have two animated values:

1. thumbnailOpacity
2. imageOpacity

And my should component update must look something like this:

state = {
   isLoading: true,
   thumbnailOpacity: new Animated.Value(0),
   imageOpacity: new Animated.Value(0)
}

shouldComponentUpdate(nextProps, nextState) {
  /*
    React's PureComponent implement a shouldComponentUpdate with shallow comparison.
    This is expensive here, because it need to check all our props. For a good bit-level performance,
    use the strictest rules for our list item.

    This component must re-render only when the state change.
  */

  return (
     nextState.isLoading !== this.state.isLoading ||
     nextState.thumbnailOpacity !== this.state.thumbnailOpacity ||
     nextState.imageOpacity !== this.state.imageOpacity
  );        
}

But as Animated values are not primitive data types, I don't know how to do that without a shallow comparison.

Any ideas? Thank you.

1

There are 1 answers

0
AvadaKedavra On

From your state initialisation:

state = {
   ...
   thumbnailOpacity: new Animated.Value(0),
   imageOpacity: new Animated.Value(0)
}

You should be able to access it like this:

this.state.thumbnailOpacity._value