Skip to content

Instantly share code, notes, and snippets.

@mmazzarolo
Last active May 20, 2023 01:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mmazzarolo/62697ec43b85b8cda1d28331ab49b9cc to your computer and use it in GitHub Desktop.
Save mmazzarolo/62697ec43b85b8cda1d28331ab49b9cc to your computer and use it in GitHub Desktop.
A basic "useAnimation" hook for React-Native animations
import { useRef } from "react";
import { Animated, Easing } from "react-native";
export const useAnimation = function(initialValue: number = 0) {
const endValue = initialValue === 0 ? 1 : 0;
const animationValueRef = useRef<Animated.Value>(new Animated.Value(initialValue));
const setup = (config: Partial<Animated.TimingAnimationConfig> = {}) =>
Animated.timing(animationValueRef.current, {
toValue: endValue,
useNativeDriver: true,
easing: Easing.inOut(Easing.quad),
...config
});
return {
value: animationValueRef.current,
setup: setup
};
};
@mmazzarolo
Copy link
Author

Example usage:

import React, { useEffect } from "react";
import { View } from "react-native";
import { useAnimation } from "./useAnimation";

const FadeInOnMount: React.FC = function() {
  const fadeAnim = useAnimation();

  useEffect(() => {
    fadeAnim.setup().start();
  }, []);

  const style = {
    opacity: fadeAnim.value,
    width: 50,
    height: 50,
    backgroundColor: "red"
  };
  return <View style={style} />;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment