Last active
September 15, 2019 16:52
-
-
Save Landerson352/952f694421c08b5c5d1aa276c97fafae to your computer and use it in GitHub Desktop.
useAnimatedValue: A hook for animating values in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
import { Animated } from 'react-native'; | |
// A hook for using react-native's Animated.Value | |
// Example usages: | |
// | |
// const animatedValue = useAnimatedValue(props.value) | |
// | |
// const animatedValue = useAnimatedValue(props.value, { method: 'spring' }) | |
// | |
// const animatedValue = useAnimatedValue( | |
// props.value, | |
// { | |
// animationConfig: { | |
// duration: 160, | |
// easing: Easing.bezier(0.7, 0, 0.7, 1), | |
// }, | |
// interpolationConfig: { | |
// inputRange: [0, 1], | |
// outputRange: ['0%', '100%'], | |
// }, | |
// } | |
// ); | |
const useAnimatedValue = (toValue, options = {}) => { | |
const { method = 'timing', animationConfig = {}, interpolationConfig } = options; | |
const animatedValue = useRef(new Animated.Value(toValue)).current; | |
useEffect(() => { | |
Animated[method]( | |
animatedValue, | |
{ | |
toValue, | |
...animationConfig, | |
} | |
).start(); | |
}, [toValue]); // eslint-disable-line react-hooks/exhaustive-deps | |
return interpolationConfig ? animatedValue.interpolate(interpolationConfig) : animatedValue; | |
}; | |
export default useAnimatedValue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment