Communitygithub.com

React Native Reanimated

Reanimated executa animações na thread nativa de UI - sem gargalo na ponte JS, sem quadros perdidos. As animações permanecem a 60fps mesmo quando a thread JavaScript está ocupada. Usa 'worklets' — pequenas funções JavaScript executadas na thread de UI através do JSI. O padrão para animações de qualidade profissional no React Native: interações guiadas por gestos, transições de layout, efeitos baseados em rolagem e transições de elementos compartilhados.

O que é React Native Reanimated?

Este skill (habilidade) fornece conhecimento especializado sobre a biblioteca React Native Reanimated, capacitando agentes de IA para criar animações de alto desempenho em aplicações React Native. A habilidade é útil pois ensina como o Reanimated contorna o gargalo da ponte JS, executando animações diretamente na thread nativa de UI via JSI e 'worklets', garantindo 60fps consistentes. O skill cobre plataformas como React Native e Expo, e mostra instruções práticas de configuração, uso de valores compartilhados (shared values), estilos animados (animated styles), animações com gestos, animações de layout e animações orientadas por rolagem. O conteúdo inclui exemplos de código detalhados, boas práticas e padrões de implementação que um agente pode aplicar para construir desde animações básicas de fade-in até interfaces complexas como cartões de swipe e bottom sheets.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/TerminalSkills/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

Reanimated executa animações na thread nativa de UI — sem gargalo na ponte JS, sem quadros perdidos. As animações permanecem a 60fps mesmo quando a thread JavaScript está ocupada. Ele usa "worklets" — pequenas funções JavaScript que executam na thread de UI via JSI. O padrão para animações de qualidade profissional no React Native: interações guiadas por gestos, transições de layout, efeitos baseados em rolagem e transições de elementos compartilhados.

Quando Usar

  • Qualquer animação no React Native além de opacidade/transformação simples
  • Interações guiadas por gestos (deslizar para excluir, arrastar para reordenar, pinçar para ampliar)
  • Animações orientadas por rolagem (cabeçalhos parallax, elementos fixos)
  • Animações de layout (itens entrando/saindo de listas)
  • Transições de elementos compartilhados entre telas

Instruções

Configuração

npx expo install react-native-reanimated react-native-gesture-handler
// babel.config.js — Adicione o plugin do Reanimated (DEVE ser o último)
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: ["react-native-reanimated/plugin"],  // Deve ser o último!
  };
};

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 { useEffect } from "react";

export function FadeInCard({ children }) {
  const opacity = useSharedValue(0);
  const translateY = useSharedValue(20);

  useEffect(() => {
    opacity.value = withTiming(1, { duration: 600 });
    translateY.value = withSpring(0, { damping: 15 });
  }, []);

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateY: translateY.value }],
  }));

  return (
    <Animated.View style={animatedStyle} className="bg-white rounded-xl p-4 shadow-lg">
      {children}
    </Animated.View>
  );
}

Animações com Gestos

// components/SwipeToDelete.tsx — Gesto de deslizar com animação
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  runOnJS,
} from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";

export function SwipeToDelete({ onDelete, children }) {
  const translateX = useSharedValue(0);

  const pan = Gesture.Pan()
    .onUpdate((event) => {
      // Apenas permite deslizar para a esquerda
      translateX.value = Math.min(0, event.translationX);
    })
    .onEnd((event) => {
      if (event.translationX < -150) {
        // Deslizou o suficiente — excluir
        translateX.value = withSpring(-400);
        runOnJS(onDelete)();
      } else {
        // Voltar ao lugar
        translateX.value = withSpring(0);
      }
    });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }],
  }));

  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={animatedStyle}>
        {children}
      </Animated.View>
    </GestureDetector>
  );
}

Animações de Layout

// components/AnimatedList.tsx — Itens animam entrada/saída automaticamente
import Animated, { FadeInDown, FadeOutLeft, LinearTransition } from "react-native-reanimated";

export function AnimatedList({ items, onRemove }) {
  return (
    <Animated.FlatList
      data={items}
      itemLayoutAnimation={LinearTransition}
      renderItem={({ item, index }) => (
        <Animated.View
          entering={FadeInDown.delay(index * 100).springify()}
          exiting={FadeOutLeft.duration(300)}
          className="bg-white p-4 mx-4 my-1 rounded-lg"
        >
          <Text>{item.title}</Text>
          <Pressable onPress={() => onRemove(item.id)}>
            <Text className="text-red-500">Remover</Text>
          </Pressable>
        </Animated.View>
      )}
    />
  );
}

Animações Orientadas por Rolagem

// components/ParallaxHeader.tsx — Efeito parallax na rolagem
import Animated, {
  useAnimatedScrollHandler,
  useSharedValue,
  useAnimatedStyle,
  interpolate,
} from "react-native-reanimated";

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]),
    opacity: interpolate(scrollY.value, [0, 200], [1, 0.3]),
    transform: [
      { translateY: interpolate(scrollY.value, [0, 200], [0, -50]) },
    ],
  }));

  return (
    <>
      <Animated.View style={headerStyle} className="bg-blue-600">
        <Text className="text-white text-3xl font-bold">Meu App</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler} scrollEventThrottle={16}>
        {/* Conteúdo */}
      </Animated.ScrollView>
    </>
  );
}

Exemplos

Exemplo 1: Construir uma interface de deslizar cartões

Prompt do usuário: "Construa uma interface de deslizar cartões estilo Tinder com animações suaves."

O agente criará uma pilha de cartões com gestos de pan, rotação baseada na direção do deslize, animações spring para voltar ao lugar e transições de layout para remoção de cartões.

Exemplo 2: Bottom sheet animado

Prompt do usuário: "Crie um bottom sheet que possa ser arrastado para cima e encaixe em posições."

O agente usará gestos pan com pontos de encaixe, valores compartilhados para altura e animações spring para encaixe suave.

Diretrizes

  • Valores compartilhados para estado de animação — useSharedValue executa na thread de UI
  • useAnimatedStyle para estilos dinâmicos — recalculado na thread de UI
  • withSpring para movimento natural — withTiming para duração precisa
  • runOnJS para chamar JS a partir de worklets — ponte de volta para a thread JS quando necessário
  • Integração com Gesture Handler — Gesture.Pan(), Gesture.Pinch(), etc.
  • Animações de layout são declarativas — props entering, exiting em componentes Animated
  • interpolate para mapeamento de valores — mapear posição de rolagem para opacidade, escala, etc.
  • Plugin Babel deve ser o último — react-native-reanimated/plugin no final do array de plugins
  • Não acessar objetos JS em worklets — apenas valores compartilhados e primitivos
  • scrollEventThrottle={16} — eventos de rolagem a 60fps para animações suaves

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

Habilidades Relacionadas