React Native Reanimated
Resumen
Reanimated ejecuta animaciones en el hilo de UI nativo, manteniendo 60fps (o la tasa de refresco de la pantalla) incluso cuando el hilo de JavaScript está ocupado. Utiliza "worklets": pequeñas funciones JavaScript que se ejecutan en el hilo de UI a través de JSI. Es el estándar para animaciones de calidad profesional en React Native: interacciones basadas en gestos, transiciones de diseño, efectos basados en desplazamiento y transiciones de elementos compartidos.
Esta habilidad está dirigida a Reanimated 4 (4.7.0, septiembre de 2026). La versión 4 solo funciona en la Nueva Arquitectura, mueve los worklets al paquete separado react-native-worklets y agrega transiciones y animaciones estilo CSS. Las aplicaciones que aún están en la arquitectura antigua deben permanecer en 3.x, que ya no recibe mantenimiento activo.
Cuándo usar
- Cualquier animación en React Native más allá de opacidad/transform simple
- Interacciones basadas en gestos (deslizar para eliminar, arrastrar para reordenar, pellizcar para hacer zoom)
- Animaciones impulsadas por desplazamiento (encabezados parallax, elementos adhesivos)
- Animaciones de diseño (elementos que entran/salen de listas)
- Transiciones de elementos compartidos entre pantallas (experimental en 4.x)
Instrucciones
Configuración
# Expo: instala las versiones fijadas por el SDK (SDK 57: Reanimated 4.5, Worklets 0.10, Gesture Handler 2.32)
npx expo install react-native-reanimated react-native-worklets react-native-gesture-handler
npx expo prebuild # solo para builds de desarrollo: regenera ios/ y android/
# React Native Community CLI
npm install react-native-reanimated react-native-worklets react-native-gesture-handler
cd ios && pod install && cd ..
npm start -- --reset-cache
- Expo:
babel-preset-expoagrega el plugin Babel de Worklets por sí mismo; no lo incluyas enbabel.config.js. - Community CLI: agrega
'react-native-worklets/plugin'como la última entrada depluginsenbabel.config.js. El nombre de Reanimated 3react-native-reanimated/pluginaún funciona en 4.x pero es la ortografía antigua. - Cada versión menor de Reanimated acepta versiones específicas de
react-native-workletsy React Native (4.7 necesita Worklets 0.13 y RN 0.86–0.88); consulta la tabla de compatibilidad antes de una actualización manual. - Para gestos, envuelve la raíz de la aplicación en
GestureHandlerRootViewdereact-native-gesture-handlerconstyle={{ flex: 1 }}.
Valores Compartidos y Estilos Animados
// components/FadeIn.tsx — Animación básica con valores compartidos
import Animated, { useSharedValue, useAnimatedStyle, withTiming, withSpring } from "react-native-reanimated";
import { type ReactNode, useEffect } from "react";
export function FadeInCard({ children }: { children: ReactNode }) {
const opacity = useSharedValue(0);
const translateY = useSharedValue(20);
useEffect(() => {
opacity.value = withTiming(1, { duration: 600 });
translateY.value = withSpring(0);
}, []);
const animatedStyle = useAnimatedStyle(() => ({
opacity: opacity.value,
transform: [{ translateY: translateY.value }],
}));
return <Animated.View style={[{ backgroundColor: "white", padding: 16 }, animatedStyle]}>{children}</Animated.View>;
}
Lee y escribe .value solo en efectos, manejadores de eventos y worklets, nunca durante el renderizado. Con el Compilador de React usa opacity.get() y opacity.set(1) en lugar de .value.
Animaciones de Gestos
// components/SwipeToDelete.tsx — Gesto de deslizar con animación
import Animated, { useSharedValue, useAnimatedStyle, withSpring } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { scheduleOnRN } from "react-native-worklets";
import type { ReactNode } from "react";
export function SwipeToDelete({ onDelete, children }: { onDelete: () => void; children: ReactNode }) {
const translateX = useSharedValue(0);
const pan = Gesture.Pan()
.onUpdate((event) => {
translateX.value = Math.min(0, event.translationX); // solo permite deslizar a la izquierda
})
.onEnd((event) => {
if (event.translationX < -150) {
translateX.value = withSpring(-400);
scheduleOnRN(onDelete); // llama a una función del hilo JS desde el hilo UI
} else {
translateX.value = withSpring(0); // regresa
}
});
const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }] }));
return (
<GestureDetector gesture={pan}>
<Animated.View style={animatedStyle}>{children}</Animated.View>
</GestureDetector>
);
}
scheduleOnRN(fn, ...args) reemplaza a runOnJS(fn)(...args), que está obsoleto en 4.x. Gesture.Pan() es la API de construcción de Gesture Handler 2, la que instala Expo SDK 57; Gesture Handler 3 la mantiene y añade hooks (usePanGesture({ onUpdate, onDeactivate }), donde onStart/onEnd se llaman onActivate/onDeactivate).
Animaciones de Diseño
// components/AnimatedList.tsx — Los elementos se animan al entrar/salir automáticamente
import Animated, { FadeInDown, FadeOutLeft, LinearTransition } from "react-native-reanimated";
import { Pressable, Text } from "react-native";
type Item = { id: string; title: string };
export function AnimatedList({ items, onRemove }: { items: Item[]; onRemove: (id: string) => void }) {
return (
<Animated.FlatList
data={items}
keyExtractor={(item) => item.id}
itemLayoutAnimation={LinearTransition} // las filas restantes se deslizan a su lugar; solo una columna
renderItem={({ item, index }) => (
<Animated.View
entering={FadeInDown.delay(index * 100).springify()}
exiting={FadeOutLeft.duration(300)}
style={{ backgroundColor: "white", padding: 16, marginVertical: 4, borderRadius: 8 }}
>
<Text>{item.title}</Text>
<Pressable onPress={() => onRemove(item.id)}><Text style={{ color: "#dc2626" }}>Eliminar</Text></Pressable>
</Animated.View>
)}
/>
);
}
Animaciones Impulsadas por Desplazamiento
// components/ParallaxHeader.tsx — Efecto parallax al hacer scroll
import Animated, {
useAnimatedScrollHandler, useSharedValue, useAnimatedStyle, interpolate, Extrapolation,
} from "react-native-reanimated";
import { Text } from "react-native";
export function ParallaxHeader() {
const scrollY = useSharedValue(0);
const scrollHandler = useAnimatedScrollHandler({
onScroll: (event) => { scrollY.value = event.contentOffset.y; },
});
const headerStyle = useAnimatedStyle(() => ({
height: interpolate(scrollY.value, [-100, 0, 200], [400, 300, 100], Extrapolation.CLAMP),
opacity: interpolate(scrollY.value, [0, 200], [1, 0.3], Extrapolation.CLAMP),
}));
return (
<>
<Animated.View style={[{ backgroundColor: "#2563eb" }, headerStyle]}>
<Text style={{ color: "white", fontSize: 28, fontWeight: "bold" }}>Registro de Senderos</Text>
</Animated.View>
<Animated.ScrollView onScroll={scrollHandler}>{/* Contenido */}</Animated.ScrollView>
</>
);
}
Cuando solo se necesita el offset, useScrollOffset(animatedRef) (llamado useScrollViewOffset en 3.x) lo devuelve como un valor compartido sin necesidad de un manejador.
Transiciones CSS y Elementos Compartidos (Reanimated 4)
// un cambio de estado se anima por sí solo: sin valor compartido, sin hook
<Animated.View
style={{
height: 80,
width: expanded ? 240 : 120,
backgroundColor: expanded ? "#16a34a" : "#2563eb",
transitionProperty: ["width", "backgroundColor"],
transitionDuration: 300,
}}
/>
// la misma etiqueta en dos pantallas de un stack nativo anima el elemento entre ellas
<Animated.Image sharedTransitionTag="trail-42-photo" source={{ uri: photoUrl }} style={{ width: 120, height: 120 }} />
Las transiciones de elementos compartidos son experimentales en 4.x y están desactivadas por defecto. Habilítalas con "reanimated": { "staticFeatureFlags": { "ENABLE_SHARED_ELEMENT_TRANSITIONS": true } } en el package.json de la aplicación (4.2+), luego reconstruye la aplicación nativa; los flags estáticos no se pueden cambiar en Expo Go.
Ejemplos
Ejemplo 1: Construir una interfaz de deslizamiento de tarjetas
Prompt del usuario: "Crea una interfaz de deslizamiento de tarjetas estilo Tinder con animaciones suaves."
// components/SwipeCard.tsx
import Animated, { interpolate, useAnimatedStyle, useSharedValue, withSpring, withTiming } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { scheduleOnRN } from "react-native-worklets";
import { useWindowDimensions } from "react-native";
import type { ReactNode } from "react";
type Props = { children: ReactNode; onSwipe: (direction: "left" | "right") => void };
export function SwipeCard({ children, onSwipe }: Props) {
const { width } = useWindowDimensions();
const x = useSharedValue(0);
const y = useSharedValue(0);
const pan = Gesture.Pan()
.onUpdate((e) => { x.value = e.translationX; y.value = e.translationY; })
.onEnd((e) => {
if (Math.abs(e.translationX) > width * 0.3) {
const direction = e.translationX > 0 ? "right" : "left";
x.value = withTiming(Math.sign(e.translationX) * width * 1.5, { duration: 200 }, (finished) => {
if (finished) scheduleOnRN(onSwipe, direction); // elimina la tarjeta en el estado de React
});
} else {
x.value = withSpring(0);
y.value = withSpring(0);
}
});
const style = useAnimatedStyle(() => ({
transform: [{ translateX: x.value }, { translateY: y.value }, { rotate: `${interpolate(x.value, [-width, 0, width], [-15, 0, 15])}deg` }],
}));
return (
<GestureDetector gesture={pan}>
<Animated.View style={style}>{children}</Animated.View>
</GestureDetector>
);
}
Resultado: la tarjeta sigue el dedo y se inclina hasta 15°. Al soltar más allá del 30% del ancho de la pantalla, vuela y se ejecuta onSwipe("left" | "right") en el hilo JS; de lo contrario, regresa al centro con un resorte.
Ejemplo 2: Hoja inferior animada
Prompt del usuario: "Crea una hoja inferior que se pueda arrastrar hacia arriba y encaje en posiciones."
// components/BottomSheet.tsx
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useWindowDimensions } from "react-native";
import type { ReactNode } from "react";
export function BottomSheet({ children }: { children: ReactNode }) {
const { height } = useWindowDimensions();
const snapPoints = [height * 0.1, height * 0.5, height * 0.85]; // borde superior: abierta, media, vista previa
const top = useSharedValue(snapPoints[2]);
const start = useSharedValue(0);
const pan = Gesture.Pan()
.onBegin(() => { start.value = top.value; })
.onUpdate((e) => { top.value = Math.max(snapPoints[0], start.value + e.translationY); })
.onEnd((e) => {
const projected = top.value + e.velocityY * 0.2; // donde aterrizaría el lanzamiento
const target = snapPoints.reduce((a, b) => (Math.abs(b - projected) < Math.abs(a - projected) ? b : a));
top.value = withSpring(target, { velocity: e.velocityY });
});
const style = useAnimatedStyle(() => ({ transform: [{ translateY: top.value }] }));
const sheet = { position: "absolute", left: 0, right: 0, top: 0, height, backgroundColor: "white" } as const;
return (
<GestureDetector gesture={pan}>
<Animated.View style={[sheet, style]}>{children}</Animated.View>
</GestureDetector>
);
}
Resultado: la hoja comienza en la posición de vista previa, sigue el arrastre y al soltarse salta al punto de encaje más cercano de los tres, teniendo en cuenta la velocidad del lanzamiento.
Directrices
- Valores compartidos para el estado de animación —
useSharedValuevive en el hilo UI; cambiarlo no vuelve a renderizar el componente useAnimatedStylepara estilos dinámicos — se recalcula en el hilo UIwithSpringpara movimiento natural —withTimingpara duración precisa. La versión 4 cambió los valores predeterminados de resorte (amortiguamiento 120, rigidez 900) y tratadurationcomo perceptual;Reanimated3DefaultSpringConfigrestaura la sensación anteriorscheduleOnRNpara llamar JS desde worklets — pasa una función definida en el ámbito del componente o módulo, no una creada dentro del worklet- Integración con Gesture Handler —
Gesture.Pan(),Gesture.Pinch(), etc.; las devoluciones de llamada pasadas en línea se convierten automáticamente en worklets, una devolución de llamada almacenada en una variable necesita una directiva'worklet'; - Las animaciones de diseño son declarativas — props
entering,exitingen componentes Animated interpolatepara mapeo de valores — mapea la posición de desplazamiento a opacidad, escala, etc.; pasaExtrapolation.CLAMPpara detenerse en los extremos del rango- El plugin Babel de Worklets debe ser el último — y después de cambiar la configuración de Babel, limpia la caché de Metro
- No captures objetos grandes en worklets — los valores capturados se copian al runtime de UI; pasa valores compartidos, primitivos y objetos pequeños simples
- Actualización desde 3.x — activa primero la Nueva Arquitectura, instala
react-native-worklets, renombra el plugin Babel y reemplazauseAnimatedGestureHandler,useWorkletCallbackycombineTransition, que se eliminaron - Cuándo no usar — un fundido o deslizamiento único que nunca bloquea puede permanecer en la API
Animatedintegrada de React Native (las transiciones CSS en nativo provienen de Reanimated); Reanimated 4 no se puede instalar en una aplicación con la arquitectura antigua