Skip to content

Instantly share code, notes, and snippets.

@Landerson352
Last active September 15, 2019 16:52
Show Gist options
  • Save Landerson352/952f694421c08b5c5d1aa276c97fafae to your computer and use it in GitHub Desktop.
Save Landerson352/952f694421c08b5c5d1aa276c97fafae to your computer and use it in GitHub Desktop.
useAnimatedValue: A hook for animating values in React Native
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