Animaciones con Reanimated
Las animaciones en React Native tienen un problema de arquitectura: el thread de JavaScript y el thread de UI son separados. Con la Animated API estándar, las animaciones se calculan en JavaScript y luego se envían al UI thread en cada frame, causando janks (saltos) si JS está ocupado.
Reanimated 2/3 resuelve esto: las animaciones se calculan directamente en el UI thread con worklets (funciones que corren en C++), logrando 60fps o 120fps sin importar qué esté haciendo JavaScript.
Reanimated usa useSharedValue para valores que se animan (equivalente a useRef pero en el UI thread) y useAnimatedStyle para calcular estilos animados. Las Gesture Handler de Reanimated permiten gestos complejos como pinch-to-zoom, swipe-to-dismiss y arrastrar elementos, todo a máxima fluidez. Para animaciones simples (transiciones entre pantallas, fade in/out), la librería Moti ofrece una API más amigable sobre Reanimated.
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
withSpring,
withRepeat,
withSequence,
Easing,
interpolate,
useAnimatedScrollHandler,
} from "react-native-reanimated";
import { Pressable } from "react-native";
export default function AnimacionesDemo() {
// Shared values corren en el UI thread
const escala = useSharedValue(1);
const opacidad = useSharedValue(1);
const rotacion = useSharedValue(0);
// Estilo animado
const estiloAnimado = useAnimatedStyle(() => ({
transform: [
{ scale: escala.value },
{ rotate: `${rotacion.value}deg` },
],
opacity: opacidad.value,
}));
const animarPresion = () => {
// Spring (rebote físico)
escala.value = withSpring(0.9, {}, () => {
escala.value = withSpring(1);
});
};
const animarRotacion = () => {
rotacion.value = withRepeat(
withTiming(360, { duration: 1000, easing: Easing.linear }),
-1 // Infinito
);
};
return (
<>
<Animated.View style={[styles.caja, estiloAnimado]}>
<Pressable onPress={animarPresion}>
<Text>Presionar</Text>
</Pressable>
</Animated.View>
<Pressable onPress={animarRotacion}>
<Text>Rotar</Text>
</Pressable>
</>
);
}
Practica esta lección
Resuelve los ejercicios del curso de React Native en la app, gratis y con corrección automática.
Empezar a practicar