Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make animatedStyle keep reference through renders (#5333)
<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please follow the template so that the reviewers can easily understand what the code changes affect. --> ## Summary Closes #1767 Some of our hooks (`useSharedValue`, `useDerivedValue`) return immutable refs. ```javascript export function useSharedValue<Value>( init: Value, oneWayReadsOnly = false ): SharedValue<Value> { const ref = useRef<SharedValue<Value>>(makeMutable(init, oneWayReadsOnly)); // code return ref.current; } ``` However `useAnimatedStyle` return an object. Therefore animated style is getting a new reference each render. This issue was noticed here: #1767 ## Test plan <details><summary>code</summary> ```javascript /* eslint-disable no-inline-styles/no-inline-styles */ import Animated, { useSharedValue, useAnimatedStyle, useDerivedValue, withSpring, } from 'react-native-reanimated'; import { Button, View } from 'react-native'; import React, { useEffect, useState } from 'react'; export default function AnimatedStyleUpdateExample() { const [, setCounter] = useState(0); const width = useSharedValue(10); const derivedValue = useDerivedValue(() => { return width.value + 10; }); const style = useAnimatedStyle(() => { return { width: width.value, }; }); useEffect(() => { setInterval(() => { setCounter((counterVal) => counterVal + 1); }, 2000); }, []); console.log('component re-render'); useEffect(() => { console.log('width changed identity'); }, [width]); useEffect(() => { console.log('derivedValue changed identity'); }, [derivedValue]); useEffect(() => { console.log('style changed identity'); }, [style]); return ( <View style={{ flex: 1, flexDirection: 'column', }}> <Animated.View style={[style, { height: 80, backgroundColor: 'black', margin: 30 }]} /> <Button title="TOGGLE" onPress={() => { width.value = withSpring(Math.random() * 100); }} /> </View> ); } ``` <details> I've tested that animations still work as desired: <summary><details>Recording</details> https://github.com/software-mansion/react-native-reanimated/assets/56199675/d2180c2d-b5a6-4736-ad94-1d245b3a5407 </summary> <!-- Provide a minimal but complete code snippet that can be used to test out this change along with instructions how to run it and a description of the expected behavior. --> --------- Co-authored-by: Aleksandra Cynk <[email protected]> Co-authored-by: Aleksandra Cynk <[email protected]> Co-authored-by: Tomasz Żelawski <[email protected]>
- Loading branch information