Communitygithub.com

React Native Reanimated

React Native Reanimated é uma biblioteca de animação para React Native que executa animações na thread da UI através de worklets e valores compartilhados, mantendo-as suaves mesmo quando a thread JavaScript está ocupada.

O que é React Native Reanimated?

React Native Reanimated é a biblioteca padrão para animações de alta qualidade em React Native, executando animações na thread nativa da UI para garantir 60fps mesmo com a thread JavaScript ocupada. Ela utiliza 'worklets' — pequenas funções JavaScript executadas na thread da UI via JSI — e valores compartilhados para animações fluidas. Esta habilidade cobre a versão 4.7.0 (Setembro 2026), que funciona apenas na Nova Arquitetura, move worklets para o pacote separado `react-native-worklets`, e adiciona transições e animações CSS. O conteúdo inclui instruções de configuração para Expo e Community CLI, exemplos práticos de animações com valores compartilhados, gestos (como swipe para deletar), animações de layout (como itens entrando/saindo de listas), animações baseadas em scroll (como parallax), e as novas transições CSS e elementos compartilhados experimentais do Reanimated 4. Também são fornecidos exemplos completos de interface de cartões estilo Tinder e bottom sheet ajustável.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que React Native Reanimated faz?

Visão Geral

O Reanimated executa animações na thread nativa da UI, mantendo-as a 60fps (ou na taxa de atualização da tela) mesmo quando a thread JavaScript está ocupada. Ele usa "worklets": pequenas funções JavaScript que executam na thread da UI via JSI. É o padrão para animações de qualidade profissional em React Native: interações baseadas em gestos, transições de layout, efeitos baseados em scroll e transições de elementos compartilhados.

Esta habilidade cobre o Reanimated 4 (4.7.0, Setembro de 2026). A versão 4 funciona apenas na Nova Arquitetura, move os worklets para o pacote separado react-native-worklets e adiciona transições e animações em estilo CSS. Aplicativos ainda na arquitetura antiga devem permanecer na versão 3.x, que não é mais mantida ativamente.

Quando Usar

  • Qualquer animação em React Native além de opacidade/transformação simples
  • Interações baseadas em gestos (deslizar para deletar, arrastar para reordenar, pinça para zoom)
  • Animações baseadas em scroll (cabeçalhos parallax, elementos fixos)
  • Animações de layout (itens entrando/saindo de listas)
  • Transições de elementos compartilhados entre telas (experimental na versão 4.x)

Instruções

Configuração

# Expo: instala as versões fixadas pelo 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        # apenas para builds de desenvolvimento: regenera ios/ e 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: o babel-preset-expo adiciona o plugin Babel do Worklets automaticamente; não o liste em babel.config.js.
  • Community CLI: adicione 'react-native-worklets/plugin' como a última entrada de plugins em babel.config.js. O nome da versão 3.x react-native-reanimated/plugin ainda funciona na 4.x, mas é a grafia legada.
  • Cada versão menor do Reanimated aceita versões específicas do react-native-worklets e do React Native (4.7 precisa de Worklets 0.13 e RN 0.86–0.88); consulte a tabela de compatibilidade antes de uma atualização manual.
  • Para gestos, envolva a raiz do aplicativo com GestureHandlerRootView do react-native-gesture-handler com style={{ flex: 1 }}.

Valores Compartilhados e Estilos Animados

// components/FadeIn.tsx — Animação básica com valores compartilhados
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>;
}

Leia e escreva .value apenas em efeitos, manipuladores de eventos e worklets, nunca durante a renderização. Com o React Compiler, use opacity.get() e opacity.set(1) em vez de .value.

Animações com Gestos

// components/SwipeToDelete.tsx — Gesto de deslizar com animação
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);   // permite apenas deslizar para a esquerda
    })
    .onEnd((event) => {
      if (event.translationX < -150) {
        translateX.value = withSpring(-400);
        scheduleOnRN(onDelete);            // chama uma função da thread JS a partir da thread da UI
      } else {
        translateX.value = withSpring(0);  // retorna ao centro
      }
    });
  const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }] }));
  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={animatedStyle}>{children}</Animated.View>
    </GestureDetector>
  );
}

scheduleOnRN(fn, ...args) substitui runOnJS(fn)(...args), que está obsoleto na versão 4.x. Gesture.Pan() é a API de construção do Gesture Handler 2, a que o Expo SDK 57 instala; o Gesture Handler 3 a mantém e adiciona hooks (usePanGesture({ onUpdate, onDeactivate }), onde onStart/onEnd são nomeados onActivate/onDeactivate).

Animações de Layout

// components/AnimatedList.tsx — Itens animam ao entrar/sair automaticamente
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}   // as linhas restantes deslizam para a posição; apenas coluna única
      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" }}>Remover</Text></Pressable>
        </Animated.View>
      )}
    />
  );
}

Animações Baseadas em Scroll

// components/ParallaxHeader.tsx — Efeito parallax ao rolar
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 Trilhas</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler}>{/* Conteúdo */}</Animated.ScrollView>
    </>
  );
}

Quando apenas o deslocamento é necessário, useScrollOffset(animatedRef) (nomeado useScrollViewOffset na versão 3.x) o retorna como um valor compartilhado sem a necessidade de um manipulador.

Transições CSS e Elementos Compartilhados (Reanimated 4)

// uma mudança de estado anima por si só: sem valor compartilhado, sem hook
<Animated.View
  style={{
    height: 80,
    width: expanded ? 240 : 120,
    backgroundColor: expanded ? "#16a34a" : "#2563eb",
    transitionProperty: ["width", "backgroundColor"],
    transitionDuration: 300,
  }}
/>

// a mesma tag em duas telas de uma pilha nativa anima o elemento entre elas
<Animated.Image sharedTransitionTag="trail-42-photo" source={{ uri: photoUrl }} style={{ width: 120, height: 120 }} />

As transições de elementos compartilhados são experimentais na versão 4.x e desativadas por padrão. Ative-as com "reanimated": { "staticFeatureFlags": { "ENABLE_SHARED_ELEMENT_TRANSITIONS": true } } no package.json do aplicativo (4.2+), depois reconstrua o aplicativo nativo; os flags estáticos não podem ser alterados no Expo Go.

Exemplos

Exemplo 1: Construir uma interface de deslizar cartões

Solicitação do usuário: "Construa uma interface de deslizar cartões estilo Tinder com animações 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);   // remove o cartão no estado do 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: o cartão segue o dedo e inclina até 15°. Solto além de 30% da largura da tela, ele voa para fora e onSwipe("left" | "right") é executado na thread JS; caso contrário, ele retorna elasticamente ao centro.

Exemplo 2: Painel inferior animado

Solicitação do usuário: "Crie um painel inferior que possa ser arrastado para cima e se encaixe em posições."

// 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]; // borda superior: aberto, meio, espiada
  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; // onde o arremesso pararia
      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: o painel começa na posição de espiada, segue o arrasto e, ao soltar, retorna elasticamente ao ponto de encaixe mais próximo dos três, levando em consideração a velocidade do arremesso.

Diretrizes

  • Valores compartilhados para estado de animação — useSharedValue vive na thread da UI; alterá-lo não causa uma re-renderização do componente
  • useAnimatedStyle para estilos dinâmicos — recalculado na thread da UI
  • withSpring para movimento natural — withTiming para duração precisa. A versão 4 alterou os padrões da mola (amortecimento 120, rigidez 900) e trata duration como perceptual; Reanimated3DefaultSpringConfig restaura a sensação antiga
  • scheduleOnRN para chamar JS a partir de worklets — passe uma função definida no escopo do componente ou módulo, não uma criada dentro do worklet
  • Integração com Gesture Handler — Gesture.Pan(), Gesture.Pinch(), etc.; callbacks passados inline são automaticamente transformados em worklets, um callback armazenado em uma variável precisa de uma diretiva 'worklet';
  • Animações de layout são declarativas — props entering, exiting em componentes Animated
  • interpolate para mapeamento de valores — mapeie a posição de rolagem para opacidade, escala, etc.; passe Extrapolation.CLAMP para parar nos limites do intervalo
  • O plugin Babel Worklets deve ser o último — e após alterar a configuração do Babel, limpe o cache do Metro
  • Não capture objetos grandes em worklets — valores capturados são copiados para o runtime da UI; passe valores compartilhados, primitivos e pequenos objetos simples
  • Atualizando da versão 3.x — ative a Nova Arquitetura primeiro, instale react-native-worklets, renomeie o plugin Babel e substitua useAnimatedGestureHandler, useWorkletCallback e combineTransition, que foram removidos
  • Quando não usar — um fade ou slide único que nunca bloqueia pode ficar na API Animated nativa do React Native (transições CSS nativas vêm do próprio Reanimated); o Reanimated 4 não pode ser instalado em um aplicativo na arquitetura antiga

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.

Habilidades Relacionadas