Communitygithub.com

React Native Reanimated

Bibliothèque d'animations React Native qui s'exécute sur le thread UI natif via des worklets et des valeurs partagées, offrant des animations fluides à 60 ips même lorsque le thread JavaScript est occupé.

Qu'est-ce que React Native Reanimated ?

React Native Reanimated est la bibliothèque standard pour les animations de haute qualité dans les applications React Native. Elle exécute les animations sur le thread UI natif en utilisant des "worklets" (petites fonctions JavaScript exécutées via JSI), garantissant ainsi un maintien de 60 ips même lorsque le thread JavaScript est chargé. Cette compétence couvre Reanimated 4 (version 4.7.0, septembre 2026), qui fonctionne exclusivement sur la Nouvelle Architecture et déplace les worklets dans le package séparé `react-native-worklets`. Elle ajoute également les transitions et animations de style CSS. Les applications encore sur l'ancienne architecture doivent utiliser la version 3.x, qui n'est plus activement maintenue. Elle est utile pour les animations de gestes (balayer pour supprimer, glisser-déposer), les animations liées au défilement (parallaxe, en-têtes), les animations de mise en page (entrée/sortie d'éléments) et les transitions d'éléments partagés entre écrans (expérimental en 4.x). Les cas d'utilisation typiques incluent la création d'interfaces comme des cartes à balayer (Tinder) ou des panneaux coulissants (bottom sheet) avec des animations fluides et réactives.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/react-native-reanimated

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Que fait React Native Reanimated ?

Vue d'ensemble

Reanimated exécute les animations sur le thread UI natif, garantissant un maintien à 60 ips (ou à la fréquence de rafraîchissement de l'écran) même lorsque le thread JavaScript est occupé. Il utilise des "worklets" : de petites fonctions JavaScript qui s'exécutent sur le thread UI via JSI. C'est la norme pour les animations de qualité production dans React Native : interactions basées sur les gestes, transitions de mise en page, effets liés au défilement et transitions d'éléments partagés.

Cette compétence cible Reanimated 4 (4.7.0, septembre 2026). La version 4 ne fonctionne que sur la Nouvelle Architecture, déplace les worklets dans le package séparé react-native-worklets, et ajoute des transitions et animations de style CSS. Les applications encore sur l'ancienne architecture doivent rester en 3.x, qui n'est plus activement maintenue.

Quand l'utiliser

  • Toute animation dans React Native au-delà d'une simple opacité/transformation
  • Interactions basées sur les gestes (balayer pour supprimer, glisser-déposer pour réorganiser, pincer pour zoomer)
  • Animations liées au défilement (en-têtes parallax, éléments collants)
  • Animations de mise en page (éléments entrant/sortant des listes)
  • Transitions d'éléments partagés entre écrans (expérimental en 4.x)

Instructions

Configuration

# Expo : installe les versions épinglées par le 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        # builds de développement uniquement : régénère ios/ et 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-expo ajoute le plugin Babel Worklets lui-même ; ne l'ajoutez pas dans babel.config.js.
  • Community CLI : ajoutez 'react-native-worklets/plugin' comme dernière entrée des plugins dans babel.config.js. Le nom Reanimated 3 react-native-reanimated/plugin fonctionne toujours en 4.x mais c'est l'orthographe héritée.
  • Chaque version mineure de Reanimated accepte des versions spécifiques de react-native-worklets et React Native (4.7 nécessite Worklets 0.13 et RN 0.86–0.88) ; consultez le tableau de compatibilité avant une mise à niveau manuelle.
  • Pour les gestes, enveloppez la racine de l'application dans GestureHandlerRootView de react-native-gesture-handler avec style={{ flex: 1 }}.

Valeurs partagées et styles animés

// components/FadeIn.tsx — Animation de base avec valeurs partagées
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>;
}

Lisez et écrivez .value uniquement dans les effets, les gestionnaires d'événements et les worklets, jamais pendant le rendu. Avec le Compilateur React, utilisez opacity.get() et opacity.set(1) au lieu de .value.

Animations gestuelles

// components/SwipeToDelete.tsx — Geste de balayage avec animation
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);   // autoriser uniquement le balayage vers la gauche
    })
    .onEnd((event) => {
      if (event.translationX < -150) {
        translateX.value = withSpring(-400);
        scheduleOnRN(onDelete);            // appeler une fonction du thread JS depuis le thread UI
      } else {
        translateX.value = withSpring(0);  // revenir en place
      }
    });
  const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }] }));
  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={animatedStyle}>{children}</Animated.View>
    </GestureDetector>
  );
}

scheduleOnRN(fn, ...args) remplace runOnJS(fn)(...args), qui est déprécié en 4.x. Gesture.Pan() est l'API de construction du Gesture Handler 2, celle qu'Expo SDK 57 installe ; Gesture Handler 3 la conserve et ajoute des hooks (usePanGesture({ onUpdate, onDeactivate }), où onStart/onEnd sont nommés onActivate/onDeactivate).

Animations de mise en page

// components/AnimatedList.tsx — Les éléments s'animent automatiquement à l'entrée/sortie
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}   // les lignes restantes glissent en place ; colonne unique uniquement
      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" }}>Supprimer</Text></Pressable>
        </Animated.View>
      )}
    />
  );
}

Animations liées au défilement

// components/ParallaxHeader.tsx — Effet parallaxe au défilement
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" }}>Journal de randonnée</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler}>{/* Contenu */}</Animated.ScrollView>
    </>
  );
}

Lorsque seul le décalage est nécessaire, useScrollOffset(animatedRef) (nommé useScrollViewOffset en 3.x) le retourne comme une valeur partagée sans gestionnaire.

Transitions CSS et éléments partagés (Reanimated 4)

// un changement d'état s'anime tout seul : pas de valeur partagée, pas de hook
<Animated.View
  style={{
    height: 80,
    width: expanded ? 240 : 120,
    backgroundColor: expanded ? "#16a34a" : "#2563eb",
    transitionProperty: ["width", "backgroundColor"],
    transitionDuration: 300,
  }}
/>

// la même balise sur deux écrans d'une pile native anime l'élément entre eux
<Animated.Image sharedTransitionTag="trail-42-photo" source={{ uri: photoUrl }} style={{ width: 120, height: 120 }} />

Les transitions d'éléments partagés sont expérimentales en 4.x et désactivées par défaut. Activez-les avec "reanimated": { "staticFeatureFlags": { "ENABLE_SHARED_ELEMENT_TRANSITIONS": true } } dans le package.json de l'application (4.2+), puis reconstruisez l'application native ; les indicateurs statiques ne peuvent pas être modifiés dans Expo Go.

Exemples

Exemple 1 : Construire une interface de cartes à balayer

Demande utilisateur : "Construis une interface de cartes à balayer de type Tinder avec des animations fluides."

// 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);   // supprimer la carte dans l'état 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>
  );
}

Résultat : la carte suit le doigt et s'incline jusqu'à 15°. Relâchée au-delà de 30% de la largeur de l'écran, elle s'envole et onSwipe("left" | "right") s'exécute sur le thread JS ; sinon, elle revient en place avec un ressort.

Exemple 2 : Panneau coulissant animé

Demande utilisateur : "Crée un panneau coulissant qui peut être glissé vers le haut et s'accroche à des positions."

// 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]; // bord supérieur : ouvert, moitié, aperçu
  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; // où le lancer atterrirait
      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>
  );
}

Résultat : le panneau commence en position d'aperçu, suit le glissement, et au relâchement revient en ressortant jusqu'au point d'accroche le plus proche parmi les trois, en tenant compte de la vélocité du lancer.

Recommandations

  • Valeurs partagées pour l'état d'animation — useSharedValue vit sur le thread UI ; sa modification ne provoque pas de nouveau rendu du composant
  • useAnimatedStyle pour les styles dynamiques — recalculé sur le thread UI
  • withSpring pour un mouvement naturel — withTiming pour une durée précise. La version 4 a modifié les valeurs par défaut du ressort (amortissement 120, raideur 900) et traite la duration comme perceptuelle ; Reanimated3DefaultSpringConfig restaure l'ancienne sensation
  • scheduleOnRN pour appeler JS depuis les worklets — passez une fonction définie dans la portée du composant ou du module, pas une fonction créée à l'intérieur du worklet
  • Intégration de Gesture Handler — Gesture.Pan(), Gesture.Pinch(), etc. ; les callbacks passés en ligne sont automatiquement transformés en worklets, un callback stocké dans une variable nécessite une directive 'worklet';
  • Les animations de mise en page sont déclaratives — propriétés entering, exiting sur les composants Animated
  • interpolate pour le mappage de valeurs — mapper la position de défilement à l'opacité, l'échelle, etc. ; passez Extrapolation.CLAMP pour vous arrêter aux extrémités de la plage
  • Le plugin Babel Worklets doit être le dernier — et après avoir modifié la configuration Babel, videz le cache Metro
  • Ne capturez pas de gros objets dans les worklets — les valeurs capturées sont copiées dans l'environnement d'exécution UI ; passez des valeurs partagées, des primitives et de petits objets simples
  • Mise à niveau depuis 3.x — activez d'abord la Nouvelle Architecture, installez react-native-worklets, renommez le plugin Babel, et remplacez useAnimatedGestureHandler, useWorkletCallback et combineTransition, qui ont été supprimés
  • Quand ne pas l'utiliser — un fondu ou un glissement ponctuel qui ne bloque jamais peut rester sur l'API Animated intégrée de React Native (les transitions CSS sur le natif viennent de Reanimated lui-même) ; Reanimated 4 ne peut pas être installé dans une application sur l'ancienne architecture

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Generate short-form videos with AI — script writing, text-to-speech narration, stock footage selection, subtitle generation, and video assembly. Use when: creating TikTok/YouTube Shorts/Reels content, automating video production, building content pipelines.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

Skills associés