Skip to content

Instantly share code, notes, and snippets.

@neolitec
Last active July 17, 2020 20:12
Show Gist options
  • Save neolitec/758ecfea73cbc87050f248859aa474c6 to your computer and use it in GitHub Desktop.
Save neolitec/758ecfea73cbc87050f248859aa474c6 to your computer and use it in GitHub Desktop.
React - useBooleanAnimation
import {Animated, Easing, EasingFunction} from 'react-native';
import {useEffect, useRef} from 'react';
const DEFAULT_ANIMATION_DURATION = 300;
const DEFAULT_EASING_FUNCTION = Easing.bezier(0.17, 0.67, 0.35, 0.92);
export function useBooleanAnimation(
value: boolean,
{
duration = DEFAULT_ANIMATION_DURATION,
easing = DEFAULT_EASING_FUNCTION,
initialValue,
useNativeDriver = true,
}: {
duration?: number;
easing?: EasingFunction;
initialValue?: boolean;
useNativeDriver?: boolean;
},
) {
const startValue = initialValue ?? value ? 1 : 0;
const baseAnimationValueRef = useRef(new Animated.Value(startValue)).current;
function buildAnimation() {
return Animated.timing(baseAnimationValueRef, {
toValue: value ? 1 : 0,
duration,
easing,
useNativeDriver,
});
}
useEffect(() => {
const animation = buildAnimation();
animation.start();
return () => animation.stop();
}, [value]);
return {
value: baseAnimationValueRef,
interpolate: (outputRange: number[] | string[]) =>
baseAnimationValueRef.interpolate({inputRange: [0, 1], outputRange}),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment