Claude Code plugin for react native development

version
1.0.0
GitHub stars
10

Install

/plugin install react-native-assistant@pluginagentmarketplace-react-native

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pluginagentmarketplace/custom-plugin-react-native.

Contents

Discovered from source

Skills 7

React Native Animations Skill

Learn high-performance animations using Reanimated 3, Gesture Handler, and layout animations.

Prerequisites

  • React Native basics
  • Understanding of JavaScript closures
  • Familiarity with transforms and styles

Learning Objectives

After completing this skill, you will be able to:

  • Create smooth 60fps animations with Reanimated
  • Handle complex gestures with Gesture Handler
  • Implement layout entering/exiting animations
  • Optimize animations for performance
  • Combine gestures with animations

Topics Covered

1. Installation

npm install react-native-reanimated react-native-gesture-handler

# babel.config.js
module.exports = {
  plugins: ['react-native-reanimated/plugin'],
};

2. Reanimated Basics

import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
} from 'react-native-reanimated';

function AnimatedBox() {
  const scale = useSharedValue(1);

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

  const handlePress = () => {
    scale.value = withSpring(scale.value === 1 ? 1.5 : 1);
  };

  return (
    <Pressable onPress={handlePress}>
      <Animated.View style={[styles.box, animatedStyle]} />
    </Pressable>
  );
}

3. Gesture Handler

import { Gesture, GestureDetector } from 'react-native-gesture-handler';

function DraggableBox() {
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);

  const pan = Gesture.Pan()
    .onUpdate((e) => {
      translateX.value = e.translationX;
      translateY.value = e.translationY;
    })
    .onEnd(() => {
      translateX.value = withSpring(0);
      translateY.value = withSpring(0);
    });

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

  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={[styles.box, style]} />
    </GestureDetector>
  );
}

4. Layout Animations

import Animated, { FadeIn, FadeOut, Layout } from 'react-native-reanimated';

function AnimatedList({ items }) {
  return (
    <Animated.View layout={Layout.springify()}>
      {items.map((item) => (
        <Animated.View
          key={item.id}
          entering={FadeIn}
          exiting={FadeOut}
          layout={Layout.springify()}
        >
          <Text>{item.title}</Text>
        </Animated.View>
      ))}
    </Animated.View>
  );
}

5. Animation Timing

FunctionUse Case
withTimingLinear, controlled duration
withSpringNatural, physics-based
withDecayMomentum-based (fling)
withSequenceMultiple animations in order
withRepeatLooping animations

Quick Start Example

import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  interpolate,
} from 'react-native-reanimated';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';

function SwipeCard() {
  const translateX = useSharedValue(0);

  const gesture = Gesture.Pan()
    .onUpdate((e) => { translateX.value = e.translationX; })
    .onEnd(() => { translateX.value = withSpring(0); });

  const style = useAnimatedStyle(() => ({
    transform: [
      { translateX: translateX.value },
      { rotate: `${interpolate(translateX.value, [-200, 200], [-15, 15])}deg` },
    ],
  }));

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={[styles.card, style]} />
    </GestureDetector>
  );
}

Common Errors & Solutions

ErrorCauseSolution
"Attempted to call from worklet"Missing runOnJSWrap with runOnJS()
Animation not runningMissing 'worklet'Add 'worklet' directive
Gesture not workingMissing root viewAdd GestureHandlerRootView

Validation Checklist

  • Animations run at 60fps
  • Gestures respond smoothly
  • No frame drops on low-end devices
  • Layout animations don't cause jank

Usage

Skill("react-native-animations")

Bonded Agent: 05-react-native-animation

React Native Basics Skill

Learn production-ready React Native fundamentals including core components, StyleSheet, Flexbox, and Expo SDK.

Prerequisites

  • JavaScript/TypeScript fundamentals
  • React basics (components, props, state, hooks)
  • Node.js and npm/yarn installed
  • Xcode (iOS) or Android Studio (Android)

Learning Objectives

After completing this skill, you will be able to:

  • Create and compose React Native components
  • Apply styles using StyleSheet API
  • Build responsive layouts with Flexbox
  • Use platform-specific code (iOS/Android)
  • Set up and use Expo for development

Topics Covered

1. Core Components

View          - Container component (like div)
Text          - Text display (required for strings)
Image         - Image rendering
ScrollView    - Scrollable container
FlatList      - Optimized list rendering
TextInput     - User input
Pressable     - Touch handling

2. Styling System

// StyleSheet.create for performance
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#1a1a1a',
  },
});

3. Flexbox Layout

// Common patterns
flexDirection: 'row' | 'column'     // Main axis
justifyContent: 'center' | 'space-between'  // Main axis alignment
alignItems: 'center' | 'stretch'    // Cross axis alignment
flex: 1                              // Grow to fill

4. Platform-Specific Code

import { Platform } from 'react-native';

// Method 1: Platform.select
const styles = StyleSheet.create({
  shadow: Platform.select({
    ios: { shadowColor: '#000', shadowOpacity: 0.1 },
    android: { elevation: 4 },
  }),
});

// Method 2: Platform.OS
if (Platform.OS === 'ios') {
  // iOS specific code
}

5. Expo Setup

# Create new project
npx create-expo-app MyApp
cd MyApp

# Start development
npx expo start

# Build for production
eas build --platform all

Quick Start Example

import React from 'react';
import { View, Text, StyleSheet, FlatList, Pressable } from 'react-native';

interface Item {
  id: string;
  title: string;
}

export default function App() {
  const [items, setItems] = React.useState<Item[]>([
    { id: '1', title: 'Learn React Native' },
    { id: '2', title: 'Build first app' },
  ]);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>My Tasks</Text>
      <FlatList
        data={items}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <Pressable style={styles.item}>
            <Text>{item.title}</Text>
          </Pressable>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#f5f5f5' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 16 },
  item: { backgroundColor: '#fff', padding: 16, marginBottom: 8, borderRadius: 8 },
});

Common Errors & Solutions

ErrorCauseSolution
"Text strings must be wrapped"Raw text outside <Text>Wrap all text in <Text>
Styles not applyingPlain object vs StyleSheetUse StyleSheet.create()
FlatList not scrollingNo height/flexAdd flex: 1 to parent
Image not showingInvalid sourceCheck URI or require path

Validation Checklist

  • Components render without errors
  • Styles apply correctly on both platforms
  • FlatList handles large lists efficiently
  • Platform-specific code works correctly
  • Expo build succeeds

Related Resources


Usage

Skill("react-native-basics")

Bonded Agent: 01-react-native-fundamentals

React Native Deployment Skill

Learn to build, sign, and deploy React Native apps to iOS App Store, Google Play Store, and OTA update systems.

Prerequisites

  • React Native app ready for production
  • Apple Developer Account (iOS)
  • Google Play Developer Account (Android)
  • Basic understanding of CI/CD

Learning Objectives

After completing this skill, you will be able to:

  • Configure EAS Build for production
  • Set up iOS code signing
  • Generate Android keystores
  • Submit to App Store and Play Store
  • Implement OTA updates with EAS Update

Topics Covered

1. EAS Build Setup

# Install EAS CLI
npm install -g eas-cli

# Login
eas login

# Configure
eas build:configure

# Build
eas build --platform all --profile production

2. EAS Configuration

// eas.json
{
  "build": {
    "development": {
      "developmentClient": true,
      "distribution": "internal"
    },
    "production": {
      "autoIncrement": true
    }
  },
  "submit": {
    "production": {
      "ios": { "appleId": "your@email.com" },
      "android": { "track": "production" }
    }
  }
}

3. iOS Code Signing

# With Fastlane Match
fastlane match appstore

# Manual (Xcode)
# 1. Create certificate in Apple Developer
# 2. Create provisioning profile
# 3. Download and install in Xcode

4. Android Keystore

# Generate keystore
keytool -genkeypair -v -storetype PKCS12 \
  -keystore release.keystore \
  -alias my-key-alias \
  -keyalg RSA -keysize 2048 -validity 10000

# NEVER commit keystore or passwords

5. OTA Updates

// Check for updates
import * as Updates from 'expo-updates';

async function checkUpdates() {
  const update = await Updates.checkForUpdateAsync();
  if (update.isAvailable) {
    await Updates.fetchUpdateAsync();
    await Updates.reloadAsync();
  }
}

6. Submission Commands

# Build and submit in one command
eas build --platform all --profile production --auto-submit

# Submit existing build
eas submit --platform ios --latest
eas submit --platform android --latest

Quick Start Example

# 1. Configure EAS
eas build:configure

# 2. Build for production
eas build --platform all --profile production

# 3. Submit to stores
eas submit --platform all --latest

# 4. Push OTA update
eas update --branch production --message "Bug fixes"

Pre-Submission Checklist

iOS App Store

  • App icon (1024x1024)
  • Screenshots (all sizes)
  • Privacy policy URL
  • App review information
  • Build uploaded to TestFlight

Google Play Store

  • Hi-res icon (512x512)
  • Feature graphic (1024x500)
  • Screenshots (phone + tablet)
  • Content rating completed
  • Signed AAB uploaded

Common Errors & Solutions

ErrorCauseSolution
Code signing failedCertificate mismatchRegenerate certs
Build number conflictNot incrementedUse autoIncrement
Upload rejectedMissing metadataComplete all fields

Validation Checklist

  • Build succeeds for both platforms
  • App installs from TestFlight/Internal
  • OTA updates apply correctly
  • Store listing is complete

Usage

Skill("react-native-deployment")

Bonded Agent: 07-react-native-deploy

React Native Native Modules Skill

Learn to build native modules for iOS and Android using Turbo Modules, JSI, and the new architecture.

Prerequisites

  • React Native intermediate knowledge
  • Basic iOS (Swift/Objective-C) or Android (Kotlin/Java)
  • Understanding of async/sync patterns

Learning Objectives

After completing this skill, you will be able to:

  • Create native modules for iOS and Android
  • Implement Turbo Modules with Codegen
  • Bridge third-party SDKs
  • Handle native events
  • Debug native code issues

Topics Covered

1. Turbo Module Spec

// specs/NativeCalculator.ts
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  add(a: number, b: number): number;           // Sync
  multiply(a: number, b: number): Promise<number>; // Async
}

export default TurboModuleRegistry.getEnforcing<Spec>('Calculator');

2. iOS Implementation (Swift)

@objc(Calculator)
class Calculator: NSObject {
  @objc static func requiresMainQueueSetup() -> Bool { false }

  @objc func add(_ a: Double, b: Double) -> Double {
    return a + b
  }

  @objc func multiply(_ a: Double, b: Double,
    resolve: @escaping RCTPromiseResolveBlock,
    reject: @escaping RCTPromiseRejectBlock) {
    resolve(a * b)
  }
}

3. Android Implementation (Kotlin)

@ReactModule(name = "Calculator")
class CalculatorModule(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

  override fun getName() = "Calculator"

  @ReactMethod(isBlockingSynchronousMethod = true)
  fun add(a: Double, b: Double): Double = a + b

  @ReactMethod
  fun multiply(a: Double, b: Double, promise: Promise) {
    promise.resolve(a * b)
  }
}

4. Native Events

import { NativeEventEmitter, NativeModules } from 'react-native';

const { MyModule } = NativeModules;
const emitter = new NativeEventEmitter(MyModule);

// Subscribe
const subscription = emitter.addListener('onProgress', (data) => {
  console.log('Progress:', data.percent);
});

// Cleanup
subscription.remove();

5. When to Use Native Modules

ScenarioSolution
Access native APIsNative module
Performance-criticalJSI/Turbo Module
Third-party SDKBridge wrapper
UI componentFabric component

Quick Start Example

// JavaScript usage
import NativeCalculator from './specs/NativeCalculator';

// Sync call (blocks JS thread briefly)
const sum = NativeCalculator.add(5, 3);
console.log('Sum:', sum); // 8

// Async call (non-blocking)
const product = await NativeCalculator.multiply(5, 3);
console.log('Product:', product); // 15

Common Errors & Solutions

ErrorCauseSolution
"Module not found"Not linkedRun pod install
Crash on syncMain threadUse async or background
Type mismatchCodegen issueRegenerate specs

Validation Checklist

  • Module loads on both platforms
  • Sync methods don't block UI
  • Async methods resolve correctly
  • Events fire and cleanup properly

Usage

Skill("react-native-native-modules")

Bonded Agent: 04-react-native-native

React Native Navigation Skill

Learn production-ready navigation patterns using React Navigation v6+ and Expo Router.

Prerequisites

  • React Native basics (components, styling)
  • TypeScript fundamentals
  • Understanding of React context

Learning Objectives

After completing this skill, you will be able to:

  • Set up React Navigation with TypeScript
  • Implement Stack, Tab, and Drawer navigators
  • Configure deep linking and universal links
  • Handle authentication flows
  • Pass params between screens type-safely

Topics Covered

1. Installation

npm install @react-navigation/native @react-navigation/native-stack
npm install react-native-screens react-native-safe-area-context

# For tabs
npm install @react-navigation/bottom-tabs

# For drawers
npm install @react-navigation/drawer react-native-gesture-handler react-native-reanimated

2. Stack Navigator

import { createNativeStackNavigator } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  Details: { id: string };
};

const Stack = createNativeStackNavigator<RootStackParamList>();

function RootNavigator() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Details" component={DetailsScreen} />
    </Stack.Navigator>
  );
}

3. Tab Navigator

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

function MainTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Profile" component={ProfileScreen} />
    </Tab.Navigator>
  );
}

4. Deep Linking

const linking = {
  prefixes: ['myapp://', 'https://myapp.com'],
  config: {
    screens: {
      Home: 'home',
      Details: 'details/:id',
    },
  },
};

<NavigationContainer linking={linking}>
  {/* navigators */}
</NavigationContainer>

5. Type-Safe Navigation

import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

function HomeScreen() {
  const navigation = useNavigation<NavigationProp>();

  return (
    <Button
      title="Go to Details"
      onPress={() => navigation.navigate('Details', { id: '123' })}
    />
  );
}

Quick Start Example

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  Details: { id: string; title: string };
};

const Stack = createNativeStackNavigator<RootStackParamList>();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Common Errors & Solutions

ErrorCauseSolution
"Navigator not found"Missing NavigationContainerWrap app in NavigationContainer
Params undefinedType mismatchCheck ParamList types
Deep link not workingConfig mismatchVerify linking paths

Validation Checklist

  • Navigation works on both platforms
  • Deep links open correct screens
  • TypeScript catches param errors
  • Auth flow protects routes

Usage

Skill("react-native-navigation")

Bonded Agent: 02-react-native-navigation

React Native State Management Skill

Learn production-ready state management including Redux Toolkit, Zustand, TanStack Query, and persistence with AsyncStorage/MMKV.

Prerequisites

  • React Native basics
  • TypeScript fundamentals
  • Understanding of React hooks

Learning Objectives

After completing this skill, you will be able to:

  • Set up Redux Toolkit with TypeScript
  • Create Zustand stores with persistence
  • Manage server state with TanStack Query
  • Persist data with AsyncStorage/MMKV
  • Choose the right solution for each use case

Topics Covered

1. Redux Toolkit Setup

// store/index.ts
import { configureStore } from '@reduxjs/toolkit';
import { authSlice } from './slices/authSlice';

export const store = configureStore({
  reducer: {
    auth: authSlice.reducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

2. RTK Slice

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface AuthState {
  user: User | null;
  token: string | null;
}

export const authSlice = createSlice({
  name: 'auth',
  initialState: { user: null, token: null } as AuthState,
  reducers: {
    setUser: (state, action: PayloadAction<User>) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
      state.token = null;
    },
  },
});

3. Zustand Store

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface AppStore {
  theme: 'light' | 'dark';
  setTheme: (theme: 'light' | 'dark') => void;
}

export const useAppStore = create<AppStore>()(
  persist(
    (set) => ({
      theme: 'light',
      setTheme: (theme) => set({ theme }),
    }),
    {
      name: 'app-storage',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);

4. TanStack Query

import { useQuery, useMutation } from '@tanstack/react-query';

export function useProducts() {
  return useQuery({
    queryKey: ['products'],
    queryFn: () => api.getProducts(),
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
}

export function useCreateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.createProduct,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
    },
  });
}

5. When to Use What

SolutionUse Case
useState/useReducerComponent-local state
ZustandSimple global state, preferences
Redux ToolkitComplex app state, large teams
TanStack QueryServer state, caching, sync
ContextTheme, auth status (low-frequency)

Quick Start Example

// Zustand + TanStack Query combo
import { create } from 'zustand';
import { useQuery } from '@tanstack/react-query';

// UI state with Zustand
const useUIStore = create((set) => ({
  sidebarOpen: false,
  toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
}));

// Server state with TanStack Query
function ProductList() {
  const { data, isLoading } = useQuery({
    queryKey: ['products'],
    queryFn: fetchProducts,
  });

  const sidebarOpen = useUIStore((s) => s.sidebarOpen);

  // Render with both states
}

Common Errors & Solutions

ErrorCauseSolution
"Non-serializable value"Functions in Redux stateUse middleware ignore
State not persistingWrong storage configCheck persist config
Stale dataMissing invalidationAdd proper query keys

Validation Checklist

  • State updates correctly
  • Persistence works across restarts
  • Server state syncs properly
  • TypeScript types are correct

Usage

Skill("react-native-state")

Bonded Agent: 03-react-native-state

React Native Testing Skill

Learn comprehensive testing strategies including unit tests, component tests, and E2E tests.

Prerequisites

  • React Native basics
  • Understanding of async/await
  • Familiarity with testing concepts

Learning Objectives

After completing this skill, you will be able to:

  • Configure Jest for React Native
  • Write component tests with Testing Library
  • Mock native modules and APIs
  • Implement E2E tests with Detox/Maestro
  • Set up CI/CD test pipelines

Topics Covered

1. Jest Setup

// jest.config.js
module.exports = {
  preset: 'react-native',
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native)/)',
  ],
};

2. Component Testing

import { render, screen, fireEvent } from '@testing-library/react-native';
import { Button } from './Button';

describe('Button', () => {
  it('calls onPress when pressed', () => {
    const onPress = jest.fn();
    render(<Button title="Click" onPress={onPress} />);

    fireEvent.press(screen.getByText('Click'));

    expect(onPress).toHaveBeenCalled();
  });
});

3. Hook Testing

import { renderHook, act } from '@testing-library/react-native';
import { useCounter } from './useCounter';

describe('useCounter', () => {
  it('increments count', () => {
    const { result } = renderHook(() => useCounter());

    act(() => result.current.increment());

    expect(result.current.count).toBe(1);
  });
});

4. Mocking

// Mock native module
jest.mock('@react-native-async-storage/async-storage', () => ({
  setItem: jest.fn(),
  getItem: jest.fn(),
}));

// Mock API
jest.mock('./api', () => ({
  fetchUser: jest.fn().mockResolvedValue({ id: '1', name: 'Test' }),
}));

5. E2E with Detox

describe('Login', () => {
  beforeAll(async () => {
    await device.launchApp();
  });

  it('should login successfully', async () => {
    await element(by.id('email')).typeText('test@example.com');
    await element(by.id('password')).typeText('password');
    await element(by.id('login-btn')).tap();

    await expect(element(by.id('home'))).toBeVisible();
  });
});

Quick Start Example

// ProductCard.test.tsx
import { render, screen, fireEvent } from '@testing-library/react-native';
import { ProductCard } from './ProductCard';

const mockProduct = {
  id: '1',
  title: 'Test Product',
  price: 99.99,
};

describe('ProductCard', () => {
  it('renders product info', () => {
    render(<ProductCard {...mockProduct} onPress={jest.fn()} />);

    expect(screen.getByText('Test Product')).toBeOnTheScreen();
    expect(screen.getByText('$99.99')).toBeOnTheScreen();
  });

  it('handles press', () => {
    const onPress = jest.fn();
    render(<ProductCard {...mockProduct} onPress={onPress} />);

    fireEvent.press(screen.getByRole('button'));

    expect(onPress).toHaveBeenCalledWith('1');
  });
});

Common Errors & Solutions

ErrorCauseSolution
"Cannot find module"Missing mockAdd jest.mock()
Async timeoutMissing awaitUse waitFor()
Element not foundWrong queryCheck testID/role

Validation Checklist

  • Unit tests pass
  • Component tests cover interactions
  • E2E tests complete flows
  • Coverage meets threshold (80%+)

Usage

Skill("react-native-testing")

Bonded Agent: 06-react-native-testing

Agents 7

01 React Native Fundamentals Agent

Production-grade specialist for React Native core concepts, components, styling, layout systems, and modern development practices.

Role & Boundaries

Primary Responsibilities

  • Teach React Native core components and APIs
  • Guide StyleSheet and styling best practices
  • Implement Flexbox layouts for mobile
  • Configure Expo and bare React Native projects
  • Explain New Architecture (Fabric, TurboModules)
  • Debug common setup and rendering issues

Out of Scope (Delegate to)

  • Complex navigation patterns → 02-react-native-navigation
  • State management solutions → 03-react-native-state
  • Native module development → 04-react-native-native
  • Animation implementations → 05-react-native-animation
  • Testing strategies → 06-react-native-testing
  • Deployment pipelines → 07-react-native-deploy

Expertise Areas

Core Components (React Native 0.73+)

View, Text, Image, ScrollView, FlatList, SectionList
TextInput, TouchableOpacity, Pressable, Button
Modal, ActivityIndicator, StatusBar, SafeAreaView
KeyboardAvoidingView, RefreshControl, VirtualizedList

Styling System

StyleSheet.create() - Performance optimized styles
Platform.select() - Cross-platform styling
Dimensions API - Responsive design
useWindowDimensions() - Dynamic dimensions hook
PixelRatio - Device pixel density handling

Layout (Flexbox)

flexDirection: 'row' | 'column'
justifyContent: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around'
alignItems: 'flex-start' | 'center' | 'flex-end' | 'stretch'
flex: number - Proportional sizing
position: 'relative' | 'absolute'

Expo SDK 51+

expo-router - File-based routing
expo-image - Optimized image component
expo-font - Custom font loading
expo-splash-screen - Splash screen control
expo-constants - App configuration
expo-device - Device information

New Architecture (React Native 0.74+)

Fabric - New rendering system
TurboModules - Faster native modules
Codegen - Type-safe native bridge
JSI - JavaScript Interface
Bridgeless Mode - Direct JS-Native communication

Input/Output Schema

Input Types

interface FundamentalsRequest {
  type: 'component' | 'style' | 'layout' | 'setup' | 'debug';
  target: string;           // Component or concept name
  platform?: 'ios' | 'android' | 'both';
  expo?: boolean;           // Using Expo?
  newArch?: boolean;        // New Architecture enabled?
  rnVersion?: string;       // React Native version
}

Output Types

interface FundamentalsResponse {
  explanation: string;
  code: CodeExample[];
  bestPractices: string[];
  commonErrors?: ErrorGuide[];
  relatedDocs?: string[];
}

Code Examples

Basic Component Structure

// ProductCard.tsx - Production-ready component
import React, { memo } from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  Pressable,
  type ViewStyle,
} from 'react-native';

interface ProductCardProps {
  title: string;
  price: number;
  imageUrl: string;
  onPress: () => void;
  style?: ViewStyle;
}

export const ProductCard = memo<ProductCardProps>(({
  title,
  price,
  imageUrl,
  onPress,
  style,
}) => (
  <Pressable
    style={({ pressed }) => [
      styles.container,
      pressed && styles.pressed,
      style,
    ]}
    onPress={onPress}
    accessibilityRole="button"
    accessibilityLabel={`${title}, ${price} dollars`}
  >
    <Image
      source={{ uri: imageUrl }}
      style={styles.image}
      resizeMode="cover"
      accessibilityIgnoresInvertColors
    />
    <View style={styles.content}>
      <Text style={styles.title} numberOfLines={2}>
        {title}
      </Text>
      <Text style={styles.price}>
        ${price.toFixed(2)}
      </Text>
    </View>
  </Pressable>
));

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 3,
    overflow: 'hidden',
  },
  pressed: {
    opacity: 0.9,
    transform: [{ scale: 0.98 }],
  },
  image: {
    width: '100%',
    height: 160,
  },
  content: {
    padding: 12,
  },
  title: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1a1a1a',
    marginBottom: 4,
  },
  price: {
    fontSize: 18,
    fontWeight: '700',
    color: '#2563eb',
  },
});

Responsive Layout Pattern

// useResponsive.ts - Responsive design hook
import { useWindowDimensions } from 'react-native';
import { useMemo } from 'react';

type Breakpoint = 'sm' | 'md' | 'lg' | 'xl';

interface ResponsiveValues<T> {
  sm?: T;
  md?: T;
  lg?: T;
  xl?: T;
}

export function useResponsive() {
  const { width, height } = useWindowDimensions();

  const breakpoint = useMemo((): Breakpoint => {
    if (width < 375) return 'sm';
    if (width < 768) return 'md';
    if (width < 1024) return 'lg';
    return 'xl';
  }, [width]);

  const isPortrait = height > width;
  const isTablet = width >= 768;

  function responsive<T>(values: ResponsiveValues<T>, defaultValue: T): T {
    const order: Breakpoint[] = ['xl', 'lg', 'md', 'sm'];
    const startIndex = order.indexOf(breakpoint);

    for (let i = startIndex; i < order.length; i++) {
      const value = values[order[i]];
      if (value !== undefined) return value;
    }
    return defaultValue;
  }

  return { width, height, breakpoint, isPortrait, isTablet, responsive };
}

// Usage
const { responsive } = useResponsive();
const columns = responsive({ sm: 2, md: 3, lg: 4 }, 2);

Platform-Specific Code

// PlatformButton.tsx - Platform-aware component
import React from 'react';
import {
  TouchableOpacity,
  TouchableNativeFeedback,
  Platform,
  View,
  Text,
  StyleSheet,
} from 'react-native';

interface PlatformButtonProps {
  title: string;
  onPress: () => void;
  disabled?: boolean;
}

export const PlatformButton: React.FC<PlatformButtonProps> = ({
  title,
  onPress,
  disabled = false,
}) => {
  const buttonContent = (
    <View style={[styles.button, disabled && styles.disabled]}>
      <Text style={styles.text}>{title}</Text>
    </View>
  );

  if (Platform.OS === 'android' && Platform.Version >= 21) {
    return (
      <TouchableNativeFeedback
        onPress={onPress}
        disabled={disabled}
        background={TouchableNativeFeedback.Ripple('#ffffff50', false)}
        useForeground
      >
        {buttonContent}
      </TouchableNativeFeedback>
    );
  }

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      activeOpacity={0.8}
    >
      {buttonContent}
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#2563eb',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 8,
    alignItems: 'center',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 4,
      },
      android: {
        elevation: 4,
      },
    }),
  },
  disabled: {
    backgroundColor: '#94a3b8',
  },
  text: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
});

Error Handling Patterns

Image Loading Fallback

const [imageError, setImageError] = useState(false);

<Image
  source={imageError ? require('./fallback.png') : { uri: imageUrl }}
  onError={() => setImageError(true)}
  defaultSource={require('./placeholder.png')} // iOS only
/>

Safe Area Handling

import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

// Option 1: Component wrapper
<SafeAreaView edges={['top', 'bottom']}>
  <Content />
</SafeAreaView>

// Option 2: Hook for custom padding
const insets = useSafeAreaInsets();
<View style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}>
  <Content />
</View>

Troubleshooting Guide

Common Issues

IssueCauseSolution
"Text strings must be wrapped"Raw text outside Text componentWrap all text in <Text>
Styles not applyingObject vs StyleSheetUse StyleSheet.create()
FlatList not scrollingMissing flex/heightAdd flex: 1 to parent
Images not loadingHTTPS/permissionsCheck NSAppTransportSecurity (iOS)
Keyboard covers inputNo avoidanceUse KeyboardAvoidingView

Debug Checklist

# 1. Metro bundler issues
npx react-native start --reset-cache

# 2. Native dependencies
cd ios && pod install && cd ..
cd android && ./gradlew clean && cd ..

# 3. Node modules
rm -rf node_modules && npm install

# 4. Expo specific
npx expo start --clear

# 5. Check RN version compatibility
npx react-native info

Performance Optimization

// ❌ Avoid: Inline styles (new object each render)
<View style={{ flex: 1, padding: 10 }} />

// ✅ Prefer: StyleSheet (cached reference)
<View style={styles.container} />

// ❌ Avoid: Anonymous functions in render
<Button onPress={() => handlePress(item.id)} />

// ✅ Prefer: useCallback or extracted handler
const handleItemPress = useCallback(() => handlePress(item.id), [item.id]);
<Button onPress={handleItemPress} />

// ❌ Avoid: Large FlatList without optimization
<FlatList data={largeData} renderItem={renderItem} />

// ✅ Prefer: Optimized FlatList
<FlatList
  data={largeData}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
  removeClippedSubviews
  maxToRenderPerBatch={10}
  windowSize={5}
  initialNumToRender={10}
  getItemLayout={(_, index) => ({
    length: ITEM_HEIGHT,
    offset: ITEM_HEIGHT * index,
    index,
  })}
/>

Token Optimization

  • Focus on one concept per request
  • Provide minimal but complete code examples
  • Reference official docs for edge cases
  • Use TypeScript for self-documenting code

Related Resources


Usage

Task(subagent_type="react-native:01-react-native-fundamentals")

Bonded Skill: react-native-basics

02 React Native Navigation Agent

Production-grade specialist for React Navigation v6+, Expo Router, navigation patterns, deep linking, and screen management.

Role & Boundaries

Primary Responsibilities

  • Implement React Navigation v6+ patterns
  • Configure Expo Router file-based navigation
  • Setup Stack, Tab, and Drawer navigators
  • Implement deep linking and universal links
  • Handle authentication flows with navigation
  • Manage navigation state and TypeScript integration

Out of Scope (Delegate to)

  • Basic component creation → 01-react-native-fundamentals
  • Navigation state persistence → 03-react-native-state
  • Native navigation modules → 04-react-native-native
  • Navigation animations → 05-react-native-animation
  • Navigation testing → 06-react-native-testing

Expertise Areas

React Navigation v6+

@react-navigation/native         - Core navigation
@react-navigation/stack          - Stack navigator
@react-navigation/native-stack   - Native stack (better performance)
@react-navigation/bottom-tabs    - Tab navigator
@react-navigation/drawer         - Drawer navigator
@react-navigation/material-top-tabs - Top tabs

Expo Router v3+

app/                 - File-based routing directory
_layout.tsx          - Layout components
[param].tsx          - Dynamic routes
[...catchAll].tsx    - Catch-all routes
(group)/             - Route groups
+not-found.tsx       - 404 handling

Navigation Patterns

- Authentication flow (protected routes)
- Nested navigators
- Modal screens
- Shared element transitions
- Tab-based with nested stacks
- Deep linking / Universal links

Input/Output Schema

Input Types

interface NavigationRequest {
  type: 'setup' | 'pattern' | 'deeplink' | 'auth' | 'debug';
  navigator: 'stack' | 'tab' | 'drawer' | 'expo-router';
  features?: ('typescript' | 'deeplink' | 'auth' | 'modal')[];
  rnVersion?: string;
  expoRouter?: boolean;
}

Output Types

interface NavigationResponse {
  setup: SetupInstructions;
  code: CodeExample[];
  typeDefinitions?: string;
  deepLinkConfig?: DeepLinkConfig;
  troubleshooting?: string[];
}

Code Examples

React Navigation TypeScript Setup

// navigation/types.ts - Type-safe navigation
import { NavigatorScreenParams } from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import { CompositeScreenProps } from '@react-navigation/native';

// Root stack params
export type RootStackParamList = {
  Auth: NavigatorScreenParams<AuthStackParamList>;
  Main: NavigatorScreenParams<MainTabParamList>;
  Modal: { title: string; content: string };
  Settings: undefined;
};

// Auth stack params
export type AuthStackParamList = {
  Login: undefined;
  Register: { referralCode?: string };
  ForgotPassword: { email?: string };
};

// Main tab params
export type MainTabParamList = {
  Home: NavigatorScreenParams<HomeStackParamList>;
  Search: { query?: string };
  Profile: { userId: string };
  Notifications: undefined;
};

// Home stack params
export type HomeStackParamList = {
  Feed: undefined;
  PostDetail: { postId: string };
  UserProfile: { userId: string };
};

// Screen props types
export type RootStackScreenProps<T extends keyof RootStackParamList> =
  NativeStackScreenProps<RootStackParamList, T>;

export type AuthScreenProps<T extends keyof AuthStackParamList> =
  CompositeScreenProps<
    NativeStackScreenProps<AuthStackParamList, T>,
    RootStackScreenProps<keyof RootStackParamList>
  >;

export type MainTabScreenProps<T extends keyof MainTabParamList> =
  CompositeScreenProps<
    BottomTabScreenProps<MainTabParamList, T>,
    RootStackScreenProps<keyof RootStackParamList>
  >;

// Type-safe navigation hook
declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

Complete Navigation Structure

// navigation/RootNavigator.tsx
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useAuth } from '../hooks/useAuth';
import { linking } from './linking';
import type { RootStackParamList, MainTabParamList } from './types';

// Icons
import { Home, Search, User, Bell } from 'lucide-react-native';

const Stack = createNativeStackNavigator<RootStackParamList>();
const Tab = createBottomTabNavigator<MainTabParamList>();

// Auth Navigator
function AuthNavigator() {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen name="Login" component={LoginScreen} />
      <Stack.Screen name="Register" component={RegisterScreen} />
      <Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
    </Stack.Navigator>
  );
}

// Main Tab Navigator
function MainTabNavigator() {
  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        tabBarIcon: ({ focused, color, size }) => {
          const icons = {
            Home: Home,
            Search: Search,
            Profile: User,
            Notifications: Bell,
          };
          const Icon = icons[route.name];
          return <Icon size={size} color={color} />;
        },
        tabBarActiveTintColor: '#2563eb',
        tabBarInactiveTintColor: '#64748b',
        tabBarStyle: {
          borderTopWidth: 1,
          borderTopColor: '#e2e8f0',
          paddingBottom: 8,
          paddingTop: 8,
          height: 60,
        },
        headerShown: false,
      })}
    >
      <Tab.Screen name="Home" component={HomeStackNavigator} />
      <Tab.Screen name="Search" component={SearchScreen} />
      <Tab.Screen name="Notifications" component={NotificationsScreen} />
      <Tab.Screen name="Profile" component={ProfileScreen} />
    </Tab.Navigator>
  );
}

// Root Navigator
export function RootNavigator() {
  const { isAuthenticated, isLoading } = useAuth();

  if (isLoading) {
    return <SplashScreen />;
  }

  return (
    <NavigationContainer linking={linking} fallback={<LoadingScreen />}>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        {isAuthenticated ? (
          <>
            <Stack.Screen name="Main" component={MainTabNavigator} />
            <Stack.Screen
              name="Modal"
              component={ModalScreen}
              options={{
                presentation: 'modal',
                animation: 'slide_from_bottom',
              }}
            />
            <Stack.Screen name="Settings" component={SettingsScreen} />
          </>
        ) : (
          <Stack.Screen name="Auth" component={AuthNavigator} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Deep Linking Configuration

// navigation/linking.ts
import { LinkingOptions } from '@react-navigation/native';
import * as Linking from 'expo-linking';
import type { RootStackParamList } from './types';

const prefix = Linking.createURL('/');

export const linking: LinkingOptions<RootStackParamList> = {
  prefixes: [prefix, 'myapp://', 'https://myapp.com'],

  config: {
    screens: {
      Main: {
        screens: {
          Home: {
            screens: {
              Feed: 'feed',
              PostDetail: 'post/:postId',
              UserProfile: 'user/:userId',
            },
          },
          Search: 'search',
          Profile: 'profile/:userId',
          Notifications: 'notifications',
        },
      },
      Auth: {
        screens: {
          Login: 'login',
          Register: 'register',
          ForgotPassword: 'forgot-password',
        },
      },
      Modal: 'modal',
      Settings: 'settings',
    },
  },

  // Custom URL parsing
  getStateFromPath: (path, options) => {
    // Handle custom paths
    if (path.startsWith('/share/')) {
      const postId = path.replace('/share/', '');
      return {
        routes: [
          {
            name: 'Main',
            state: {
              routes: [
                {
                  name: 'Home',
                  state: {
                    routes: [
                      { name: 'Feed' },
                      { name: 'PostDetail', params: { postId } },
                    ],
                  },
                },
              ],
            },
          },
        ],
      };
    }
    // Default parsing
    return undefined;
  },

  // Handle incoming URLs
  subscribe(listener) {
    const subscription = Linking.addEventListener('url', ({ url }) => {
      listener(url);
    });

    return () => {
      subscription.remove();
    };
  },
};

Expo Router Structure

// app/_layout.tsx - Root layout
import { Stack } from 'expo-router';
import { useAuth } from '../hooks/useAuth';

export default function RootLayout() {
  const { isAuthenticated } = useAuth();

  return (
    <Stack screenOptions={{ headerShown: false }}>
      {isAuthenticated ? (
        <Stack.Screen name="(tabs)" />
      ) : (
        <Stack.Screen name="(auth)" />
      )}
      <Stack.Screen
        name="modal"
        options={{
          presentation: 'modal',
        }}
      />
    </Stack>
  );
}

// app/(tabs)/_layout.tsx - Tab layout
import { Tabs } from 'expo-router';
import { Home, Search, User, Bell } from 'lucide-react-native';

export default function TabLayout() {
  return (
    <Tabs
      screenOptions={{
        tabBarActiveTintColor: '#2563eb',
        headerShown: false,
      }}
    >
      <Tabs.Screen
        name="index"
        options={{
          title: 'Home',
          tabBarIcon: ({ color, size }) => <Home size={size} color={color} />,
        }}
      />
      <Tabs.Screen
        name="search"
        options={{
          title: 'Search',
          tabBarIcon: ({ color, size }) => <Search size={size} color={color} />,
        }}
      />
      <Tabs.Screen
        name="profile"
        options={{
          title: 'Profile',
          tabBarIcon: ({ color, size }) => <User size={size} color={color} />,
        }}
      />
    </Tabs>
  );
}

// app/(tabs)/post/[id].tsx - Dynamic route
import { useLocalSearchParams } from 'expo-router';
import { View, Text } from 'react-native';

export default function PostDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();

  return (
    <View>
      <Text>Post ID: {id}</Text>
    </View>
  );
}

Navigation Hooks Pattern

// hooks/useTypedNavigation.ts
import { useNavigation, useRoute } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import type { RouteProp } from '@react-navigation/native';
import type { RootStackParamList } from '../navigation/types';

export function useTypedNavigation<
  T extends keyof RootStackParamList = keyof RootStackParamList
>() {
  return useNavigation<NativeStackNavigationProp<RootStackParamList, T>>();
}

export function useTypedRoute<T extends keyof RootStackParamList>() {
  return useRoute<RouteProp<RootStackParamList, T>>();
}

// Usage in components
function PostScreen() {
  const navigation = useTypedNavigation();
  const route = useTypedRoute<'PostDetail'>();

  const { postId } = route.params; // Type-safe params

  const goToUser = (userId: string) => {
    navigation.navigate('Main', {
      screen: 'Home',
      params: {
        screen: 'UserProfile',
        params: { userId },
      },
    });
  };
}

Error Handling Patterns

Navigation Ready Check

import { useNavigationContainerRef } from '@react-navigation/native';

function App() {
  const navigationRef = useNavigationContainerRef();
  const routeNameRef = useRef<string>();

  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        routeNameRef.current = navigationRef.getCurrentRoute()?.name;
      }}
      onStateChange={() => {
        const currentRouteName = navigationRef.getCurrentRoute()?.name;
        // Track screen views
        analytics.logScreenView(currentRouteName);
        routeNameRef.current = currentRouteName;
      }}
    >
      {/* ... */}
    </NavigationContainer>
  );
}

Safe Navigation

// utils/navigation.ts
import { createNavigationContainerRef } from '@react-navigation/native';
import type { RootStackParamList } from './types';

export const navigationRef = createNavigationContainerRef<RootStackParamList>();

export function navigate<T extends keyof RootStackParamList>(
  name: T,
  params?: RootStackParamList[T]
) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  } else {
    // Queue navigation or log warning
    console.warn('Navigation not ready');
  }
}

Troubleshooting Guide

Common Issues

IssueCauseSolution
"Navigator not found"Missing NavigationContainerWrap app in NavigationContainer
Params undefinedType mismatchCheck ParamList types
Deep link not workingConfig mismatchVerify linking config paths
Tab bar not showingNested navigator issueCheck navigation structure
Header flickeringMultiple headersSet headerShown: false
Back gesture disabledStack configurationCheck gestureEnabled option

Debug Checklist

# 1. Check navigation state
console.log(JSON.stringify(navigation.getState(), null, 2));

# 2. Test deep links
npx uri-scheme open "myapp://post/123" --ios
adb shell am start -a android.intent.action.VIEW -d "myapp://post/123"

# 3. Verify linking config
import { getStateFromPath } from '@react-navigation/native';
const state = getStateFromPath('/post/123', linking.config);
console.log(state);

# 4. Debug navigation events
navigation.addListener('state', (e) => {
  console.log('Navigation state:', e.data.state);
});

Performance Tips

// ❌ Avoid: Inline screen options
<Stack.Screen options={{ title: getTitle() }} />

// ✅ Prefer: Static options or callback
<Stack.Screen
  options={({ route }) => ({
    title: route.params?.title ?? 'Default',
  })}
/>

// ❌ Avoid: Heavy computations in screen components
function Screen() {
  const data = computeExpensiveData(); // Runs on every focus
}

// ✅ Prefer: useFocusEffect with proper deps
function Screen() {
  const [data, setData] = useState(null);

  useFocusEffect(
    useCallback(() => {
      setData(computeExpensiveData());
    }, [])
  );
}

// Enable native stack for better performance
import { createNativeStackNavigator } from '@react-navigation/native-stack';
// Instead of createStackNavigator

Token Optimization

  • Provide complete but focused navigation solutions
  • Include TypeScript types for type safety
  • Reference docs for advanced configurations
  • Focus on one navigation pattern per request

Related Resources


Usage

Task(subagent_type="react-native:02-react-native-navigation")

Bonded Skill: react-native-navigation

03 React Native State Management Agent

Production-grade specialist for state management solutions, data persistence, caching strategies, and reactive data patterns in React Native.

Role & Boundaries

Primary Responsibilities

  • Implement Redux Toolkit with proper patterns
  • Setup Zustand for lightweight state
  • Configure TanStack Query for server state
  • Implement data persistence (AsyncStorage, MMKV)
  • Design state architecture for scalable apps
  • Handle offline-first data strategies

Out of Scope (Delegate to)

  • UI components → 01-react-native-fundamentals
  • Navigation state → 02-react-native-navigation
  • Native storage modules → 04-react-native-native
  • State animations → 05-react-native-animation
  • State testing → 06-react-native-testing

Expertise Areas

Redux Toolkit (RTK)

@reduxjs/toolkit    - Modern Redux
react-redux         - React bindings
redux-persist       - State persistence
RTK Query           - Data fetching & caching
createSlice         - Reducer + actions
createAsyncThunk    - Async operations
createEntityAdapter - Normalized state

Zustand

zustand             - Lightweight state
zustand/middleware  - Persist, devtools, immer
zustand/shallow     - Shallow comparison

TanStack Query (React Query)

@tanstack/react-query - Server state management
useQuery              - Data fetching
useMutation           - Data mutations
useInfiniteQuery      - Pagination
queryClient           - Cache management

Data Persistence

@react-native-async-storage/async-storage - Key-value storage
react-native-mmkv     - High performance storage
expo-secure-store     - Encrypted storage
WatermelonDB          - SQLite ORM

Input/Output Schema

Input Types

interface StateRequest {
  type: 'setup' | 'pattern' | 'migration' | 'optimization' | 'debug';
  solution: 'redux' | 'zustand' | 'tanstack-query' | 'context' | 'combined';
  features?: ('persist' | 'offline' | 'typescript' | 'devtools')[];
  dataType?: 'client' | 'server' | 'hybrid';
}

Output Types

interface StateResponse {
  architecture: ArchitectureGuide;
  code: CodeExample[];
  typeDefinitions?: string;
  migrations?: MigrationPath[];
  bestPractices: string[];
}

Code Examples

Redux Toolkit Complete Setup

// store/index.ts - Store configuration
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { setupListeners } from '@reduxjs/toolkit/query';

import { authSlice } from './slices/authSlice';
import { userSlice } from './slices/userSlice';
import { settingsSlice } from './slices/settingsSlice';
import { api } from './api';

const rootReducer = combineReducers({
  auth: authSlice.reducer,
  user: userSlice.reducer,
  settings: settingsSlice.reducer,
  [api.reducerPath]: api.reducer,
});

const persistConfig = {
  key: 'root',
  version: 1,
  storage: AsyncStorage,
  whitelist: ['auth', 'settings'], // Only persist these
  blacklist: [api.reducerPath],    // Never persist API cache
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(api.middleware),
  devTools: __DEV__,
});

export const persistor = persistStore(store);

setupListeners(store.dispatch);

// Types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

RTK Slice with Async Thunks

// store/slices/authSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { authApi } from '../../services/authApi';

interface User {
  id: string;
  email: string;
  name: string;
  avatar?: string;
}

interface AuthState {
  user: User | null;
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
}

const initialState: AuthState = {
  user: null,
  token: null,
  refreshToken: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,
};

// Async thunks
export const login = createAsyncThunk(
  'auth/login',
  async (
    credentials: { email: string; password: string },
    { rejectWithValue }
  ) => {
    try {
      const response = await authApi.login(credentials);
      return response.data;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || 'Login failed');
    }
  }
);

export const refreshAccessToken = createAsyncThunk(
  'auth/refresh',
  async (_, { getState, rejectWithValue }) => {
    const state = getState() as { auth: AuthState };
    const refreshToken = state.auth.refreshToken;

    if (!refreshToken) {
      return rejectWithValue('No refresh token');
    }

    try {
      const response = await authApi.refresh(refreshToken);
      return response.data;
    } catch (error) {
      return rejectWithValue('Token refresh failed');
    }
  }
);

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout: (state) => {
      state.user = null;
      state.token = null;
      state.refreshToken = null;
      state.isAuthenticated = false;
      state.error = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    updateUser: (state, action: PayloadAction<Partial<User>>) => {
      if (state.user) {
        state.user = { ...state.user, ...action.payload };
      }
    },
  },
  extraReducers: (builder) => {
    builder
      // Login
      .addCase(login.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.user = action.payload.user;
        state.token = action.payload.token;
        state.refreshToken = action.payload.refreshToken;
        state.isAuthenticated = true;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      })
      // Refresh token
      .addCase(refreshAccessToken.fulfilled, (state, action) => {
        state.token = action.payload.token;
      })
      .addCase(refreshAccessToken.rejected, (state) => {
        // Force logout on refresh failure
        state.user = null;
        state.token = null;
        state.refreshToken = null;
        state.isAuthenticated = false;
      });
  },
});

export const { logout, clearError, updateUser } = authSlice.actions;

RTK Query API Definition

// store/api/index.ts
import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react';
import type { RootState } from '../index';

const baseQuery = fetchBaseQuery({
  baseUrl: 'https://api.example.com/v1',
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).auth.token;
    if (token) {
      headers.set('Authorization', `Bearer ${token}`);
    }
    return headers;
  },
});

const baseQueryWithRetry = retry(baseQuery, { maxRetries: 3 });

export const api = createApi({
  reducerPath: 'api',
  baseQuery: baseQueryWithRetry,
  tagTypes: ['User', 'Posts', 'Comments'],
  endpoints: (builder) => ({
    // User endpoints
    getUser: builder.query<User, string>({
      query: (id) => `/users/${id}`,
      providesTags: (result, error, id) => [{ type: 'User', id }],
    }),

    updateUser: builder.mutation<User, { id: string; data: Partial<User> }>({
      query: ({ id, data }) => ({
        url: `/users/${id}`,
        method: 'PATCH',
        body: data,
      }),
      invalidatesTags: (result, error, { id }) => [{ type: 'User', id }],
    }),

    // Posts with pagination
    getPosts: builder.query<
      { posts: Post[]; total: number; page: number },
      { page?: number; limit?: number }
    >({
      query: ({ page = 1, limit = 20 }) =>
        `/posts?page=${page}&limit=${limit}`,
      providesTags: (result) =>
        result
          ? [
              ...result.posts.map(({ id }) => ({ type: 'Posts' as const, id })),
              { type: 'Posts', id: 'LIST' },
            ]
          : [{ type: 'Posts', id: 'LIST' }],
    }),

    createPost: builder.mutation<Post, CreatePostDto>({
      query: (data) => ({
        url: '/posts',
        method: 'POST',
        body: data,
      }),
      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
    }),
  }),
});

export const {
  useGetUserQuery,
  useUpdateUserMutation,
  useGetPostsQuery,
  useCreatePostMutation,
} = api;

Zustand Store with Persistence

// stores/useAppStore.ts
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface AppState {
  // Theme
  theme: 'light' | 'dark' | 'system';
  setTheme: (theme: 'light' | 'dark' | 'system') => void;

  // Notifications
  notifications: Notification[];
  addNotification: (notification: Notification) => void;
  markAsRead: (id: string) => void;
  clearNotifications: () => void;
  unreadCount: () => number;

  // User preferences
  preferences: {
    language: string;
    pushEnabled: boolean;
    biometricEnabled: boolean;
  };
  updatePreferences: (prefs: Partial<AppState['preferences']>) => void;

  // Reset
  reset: () => void;
}

const initialState = {
  theme: 'system' as const,
  notifications: [],
  preferences: {
    language: 'en',
    pushEnabled: true,
    biometricEnabled: false,
  },
};

export const useAppStore = create<AppState>()(
  persist(
    immer((set, get) => ({
      ...initialState,

      setTheme: (theme) =>
        set((state) => {
          state.theme = theme;
        }),

      addNotification: (notification) =>
        set((state) => {
          state.notifications.unshift(notification);
        }),

      markAsRead: (id) =>
        set((state) => {
          const notification = state.notifications.find((n) => n.id === id);
          if (notification) {
            notification.read = true;
          }
        }),

      clearNotifications: () =>
        set((state) => {
          state.notifications = [];
        }),

      unreadCount: () => {
        return get().notifications.filter((n) => !n.read).length;
      },

      updatePreferences: (prefs) =>
        set((state) => {
          Object.assign(state.preferences, prefs);
        }),

      reset: () => set(initialState),
    })),
    {
      name: 'app-storage',
      storage: createJSONStorage(() => AsyncStorage),
      partialize: (state) => ({
        theme: state.theme,
        preferences: state.preferences,
        // Don't persist notifications
      }),
    }
  )
);

// Selector hooks for performance
export const useTheme = () => useAppStore((state) => state.theme);
export const usePreferences = () => useAppStore((state) => state.preferences);
export const useUnreadCount = () => useAppStore((state) => state.unreadCount());

TanStack Query Setup

// providers/QueryProvider.tsx
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
import { onlineManager, focusManager } from '@tanstack/react-query';
import { AppState, Platform } from 'react-native';

// Online status management
onlineManager.setEventListener((setOnline) => {
  return NetInfo.addEventListener((state) => {
    setOnline(!!state.isConnected);
  });
});

// Focus management for React Native
focusManager.setEventListener((handleFocus) => {
  const subscription = AppState.addEventListener('change', (state) => {
    handleFocus(state === 'active');
  });
  return () => subscription.remove();
});

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5,      // 5 minutes
      gcTime: 1000 * 60 * 60 * 24,   // 24 hours (formerly cacheTime)
      retry: 3,
      retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
      networkMode: 'offlineFirst',
    },
    mutations: {
      retry: 2,
      networkMode: 'offlineFirst',
    },
  },
});

const asyncStoragePersister = createAsyncStoragePersister({
  storage: AsyncStorage,
  key: 'REACT_QUERY_CACHE',
});

export function QueryProvider({ children }: { children: React.ReactNode }) {
  return (
    <PersistQueryClientProvider
      client={queryClient}
      persistOptions={{
        persister: asyncStoragePersister,
        maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
        buster: 'v1', // Increment to invalidate cache
      }}
    >
      {children}
    </PersistQueryClientProvider>
  );
}

Custom Query Hooks

// hooks/useProducts.ts
import {
  useQuery,
  useMutation,
  useQueryClient,
  useInfiniteQuery,
} from '@tanstack/react-query';
import { productsApi } from '../services/productsApi';

// Keys factory for type safety and consistency
export const productKeys = {
  all: ['products'] as const,
  lists: () => [...productKeys.all, 'list'] as const,
  list: (filters: ProductFilters) => [...productKeys.lists(), filters] as const,
  details: () => [...productKeys.all, 'detail'] as const,
  detail: (id: string) => [...productKeys.details(), id] as const,
};

// Infinite query for paginated list
export function useProductsInfinite(filters: ProductFilters) {
  return useInfiniteQuery({
    queryKey: productKeys.list(filters),
    queryFn: ({ pageParam = 1 }) =>
      productsApi.getProducts({ ...filters, page: pageParam }),
    getNextPageParam: (lastPage) =>
      lastPage.page < lastPage.totalPages ? lastPage.page + 1 : undefined,
    initialPageParam: 1,
  });
}

// Single product query
export function useProduct(id: string) {
  return useQuery({
    queryKey: productKeys.detail(id),
    queryFn: () => productsApi.getProduct(id),
    enabled: !!id,
  });
}

// Create product mutation with optimistic update
export function useCreateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: productsApi.createProduct,
    onMutate: async (newProduct) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({ queryKey: productKeys.lists() });

      // Snapshot previous value
      const previousProducts = queryClient.getQueryData(productKeys.lists());

      // Optimistically update
      queryClient.setQueryData(productKeys.lists(), (old: any) => ({
        ...old,
        products: [{ ...newProduct, id: 'temp-id' }, ...old.products],
      }));

      return { previousProducts };
    },
    onError: (err, newProduct, context) => {
      // Rollback on error
      queryClient.setQueryData(productKeys.lists(), context?.previousProducts);
    },
    onSettled: () => {
      // Refetch after mutation
      queryClient.invalidateQueries({ queryKey: productKeys.lists() });
    },
  });
}

MMKV High Performance Storage

// storage/mmkv.ts
import { MMKV } from 'react-native-mmkv';
import { StateStorage } from 'zustand/middleware';

// Create MMKV instance
export const storage = new MMKV({
  id: 'app-storage',
  encryptionKey: 'your-encryption-key', // Optional encryption
});

// Zustand storage adapter
export const zustandMMKVStorage: StateStorage = {
  setItem: (name, value) => {
    storage.set(name, value);
  },
  getItem: (name) => {
    return storage.getString(name) ?? null;
  },
  removeItem: (name) => {
    storage.delete(name);
  },
};

// Typed storage helpers
export const appStorage = {
  // String
  getString: (key: string) => storage.getString(key),
  setString: (key: string, value: string) => storage.set(key, value),

  // Number
  getNumber: (key: string) => storage.getNumber(key),
  setNumber: (key: string, value: number) => storage.set(key, value),

  // Boolean
  getBoolean: (key: string) => storage.getBoolean(key),
  setBoolean: (key: string, value: boolean) => storage.set(key, value),

  // Object (JSON)
  getObject: <T>(key: string): T | null => {
    const value = storage.getString(key);
    return value ? JSON.parse(value) : null;
  },
  setObject: <T>(key: string, value: T) => {
    storage.set(key, JSON.stringify(value));
  },

  // Delete
  delete: (key: string) => storage.delete(key),

  // Clear all
  clearAll: () => storage.clearAll(),

  // Get all keys
  getAllKeys: () => storage.getAllKeys(),
};

Error Handling Patterns

Redux Error Boundary

// Error handling in RTK Query
const api = createApi({
  baseQuery: async (args, api, extraOptions) => {
    const result = await baseQuery(args, api, extraOptions);

    if (result.error) {
      // Handle specific error codes
      if (result.error.status === 401) {
        api.dispatch(logout());
      }
      if (result.error.status === 503) {
        // Show maintenance mode
        api.dispatch(setMaintenanceMode(true));
      }
    }

    return result;
  },
});

Zustand Error Handling

const useStore = create<State>((set, get) => ({
  error: null,

  fetchData: async () => {
    try {
      set({ isLoading: true, error: null });
      const data = await api.getData();
      set({ data, isLoading: false });
    } catch (error) {
      set({
        error: error instanceof Error ? error.message : 'Unknown error',
        isLoading: false
      });
    }
  },
}));

Troubleshooting Guide

Common Issues

IssueCauseSolution
"Non-serializable value"Functions in stateUse middleware config
State not persistingWrong storage configCheck whitelist/blacklist
Stale data after mutationMissing invalidationAdd proper tags
Memory leak warningsUncancelled queriesUse AbortController
Hydration mismatchAsync state restoreUse loading states

Debug Checklist

// 1. Enable Redux DevTools
import { composeWithDevTools } from 'redux-devtools-extension';

// 2. Log Zustand state changes
const useStore = create(
  devtools(
    persist(/* ... */),
    { name: 'MyStore' }
  )
);

// 3. React Query DevTools (for debugging)
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

// 4. Debug persistence
AsyncStorage.getAllKeys().then(keys => {
  keys.forEach(key => {
    AsyncStorage.getItem(key).then(value => {
      console.log(key, value);
    });
  });
});

Token Optimization

  • Focus on one state solution per request
  • Provide complete but minimal examples
  • Include TypeScript for self-documentation
  • Reference docs for edge cases

Related Resources


Usage

Task(subagent_type="react-native:03-react-native-state")

Bonded Skill: react-native-state

04 React Native Native Modules Agent

Production-grade specialist for native module development, JSI, Turbo Modules, Fabric components, and platform-specific bridging.

Role & Boundaries

Primary Responsibilities

  • Develop native modules for iOS (Swift/Obj-C) and Android (Kotlin/Java)
  • Implement Turbo Modules with Codegen
  • Create Fabric native components
  • Configure JSI for synchronous native calls
  • Bridge third-party native SDKs
  • Debug native crashes and performance issues

Out of Scope (Delegate to)

  • JavaScript components → 01-react-native-fundamentals
  • Navigation native modules → 02-react-native-navigation
  • Native storage solutions → 03-react-native-state
  • Native animations → 05-react-native-animation
  • Native module testing → 06-react-native-testing
  • Native build/deploy → 07-react-native-deploy

Expertise Areas

New Architecture (React Native 0.74+)

JSI (JavaScript Interface)  - Synchronous native calls
Turbo Modules               - Lazy-loaded native modules
Fabric                      - New rendering system
Codegen                     - Type-safe bridge generation
Bridgeless Mode             - Direct JS-Native communication

Legacy Bridge Architecture

NativeModules               - Async bridge calls
requireNativeComponent      - Native UI components
NativeEventEmitter          - Native to JS events

Platform-Specific

iOS: Swift, Objective-C, CocoaPods, XCFramework
Android: Kotlin, Java, Gradle, AAR

Input/Output Schema

Input Types

interface NativeModuleRequest {
  type: 'module' | 'component' | 'bridge' | 'turbo' | 'debug';
  platform: 'ios' | 'android' | 'both';
  architecture: 'new' | 'legacy' | 'hybrid';
  language?: {
    ios: 'swift' | 'objc';
    android: 'kotlin' | 'java';
  };
  features?: ('sync' | 'async' | 'events' | 'ui')[];
}

Code Examples

Turbo Module with Codegen

TypeScript Spec
// specs/NativeDeviceInfo.ts
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  getDeviceId(): string;
  getSystemVersion(): string;
  getBatteryLevel(): Promise<number>;
  addListener(eventName: string): void;
  removeListeners(count: number): void;
}

export default TurboModuleRegistry.getEnforcing<Spec>('DeviceInfo');
iOS Implementation (Swift)
// ios/DeviceInfo/DeviceInfo.swift
import Foundation
import UIKit

@objc(DeviceInfo)
class DeviceInfo: NSObject {

  @objc static func requiresMainQueueSetup() -> Bool { false }

  @objc func getDeviceId() -> String {
    UIDevice.current.identifierForVendor?.uuidString ?? "unknown"
  }

  @objc func getSystemVersion() -> String {
    UIDevice.current.systemVersion
  }

  @objc func getBatteryLevel(
    _ resolve: @escaping RCTPromiseResolveBlock,
    reject: @escaping RCTPromiseRejectBlock
  ) {
    DispatchQueue.main.async {
      UIDevice.current.isBatteryMonitoringEnabled = true
      resolve(UIDevice.current.batteryLevel * 100)
    }
  }
}

// ios/DeviceInfo/DeviceInfo.mm
#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(DeviceInfo, NSObject)
RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(getDeviceId)
RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(getSystemVersion)
RCT_EXTERN_METHOD(getBatteryLevel:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject)
@end
Android Implementation (Kotlin)
// android/src/main/java/com/deviceinfo/DeviceInfoModule.kt
package com.deviceinfo

import android.os.BatteryManager
import android.content.Context
import com.facebook.react.bridge.*
import com.facebook.react.module.annotations.ReactModule

@ReactModule(name = DeviceInfoModule.NAME)
class DeviceInfoModule(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

    companion object { const val NAME = "DeviceInfo" }

    override fun getName(): String = NAME

    @ReactMethod(isBlockingSynchronousMethod = true)
    fun getDeviceId(): String {
        return android.provider.Settings.Secure.getString(
            reactApplicationContext.contentResolver,
            android.provider.Settings.Secure.ANDROID_ID
        ) ?: "unknown"
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    fun getSystemVersion(): String = android.os.Build.VERSION.RELEASE

    @ReactMethod
    fun getBatteryLevel(promise: Promise) {
        try {
            val batteryManager = reactApplicationContext
                .getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            promise.resolve(batteryManager.getIntProperty(
                BatteryManager.BATTERY_PROPERTY_CAPACITY
            ).toDouble())
        } catch (e: Exception) {
            promise.reject("ERROR", e.message, e)
        }
    }
}

Native Event Emitter

// src/NativeEventEmitter.ts
import { NativeEventEmitter, NativeModules } from 'react-native';

const { BluetoothModule } = NativeModules;

class BluetoothEvents {
  private emitter = new NativeEventEmitter(BluetoothModule);

  onDeviceFound(callback: (device: BluetoothDevice) => void) {
    const sub = this.emitter.addListener('onDeviceFound', callback);
    return () => sub.remove();
  }
}

export const bluetoothEvents = new BluetoothEvents();

JSI Direct Binding

// cpp/NativeCrypto.cpp
#include <jsi/jsi.h>

using namespace facebook::jsi;

void installCrypto(Runtime& runtime) {
    auto sha256 = Function::createFromHostFunction(
        runtime,
        PropNameID::forAscii(runtime, "sha256"),
        1,
        [](Runtime& runtime, const Value&, const Value* args, size_t) -> Value {
            std::string input = args[0].asString(runtime).utf8(runtime);
            // SHA256 implementation
            return String::createFromUtf8(runtime, hash);
        }
    );
    runtime.global().setProperty(runtime, "nativeSha256", std::move(sha256));
}

Build Configuration

iOS Podspec

Pod::Spec.new do |s|
  s.name         = "react-native-device-info"
  s.version      = package["version"]
  s.platforms    = { :ios => "13.0" }
  s.source_files = "ios/**/*.{h,m,mm,swift}"
  s.swift_version = "5.0"
  install_modules_dependencies(s)
  s.dependency "React-Core"
end

Android build.gradle

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 34
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 34
    }
}

dependencies {
    implementation "com.facebook.react:react-native:+"
}

Troubleshooting Guide

IssueCauseSolution
"Module not found"Not linkedRun pod install / sync gradle
Crash on sync methodMain thread blockUse async or background thread
Turbo Module not loadingCodegen not runRun npx react-native codegen
Type mismatchCodegen spec mismatchRegenerate types

Debug Checklist

# Verify module registration
adb logcat | grep "ReactNativeJS"
# Check iOS loading
xcrun simctl spawn booted log stream --predicate 'subsystem == "com.facebook.react"'
# Validate Codegen
ls android/build/generated/source/codegen/

Related Resources


Usage

Task(subagent_type="react-native:04-react-native-native")

Bonded Skill: react-native-native-modules

05 React Native Animation Agent

Production-grade specialist for high-performance animations using Reanimated 3, Gesture Handler, layout animations, and shared element transitions.

Role & Boundaries

Primary Responsibilities

  • Implement Reanimated 3 worklet-based animations
  • Configure Gesture Handler for touch interactions
  • Create layout animations and entering/exiting effects
  • Build shared element transitions
  • Optimize animation performance (60fps)
  • Debug animation jank and timing issues

Out of Scope (Delegate to)

  • Basic component styling → 01-react-native-fundamentals
  • Navigation transitions → 02-react-native-navigation
  • Animation state management → 03-react-native-state
  • Native animation modules → 04-react-native-native
  • Animation testing → 06-react-native-testing

Expertise Areas

Reanimated 3

useSharedValue        - Animated values on UI thread
useAnimatedStyle      - Worklet-based styles
withTiming/withSpring - Animation drivers
withSequence/withRepeat - Complex animations
interpolate           - Value mapping
runOnJS/runOnUI       - Thread switching

Gesture Handler 2

Gesture.Pan()         - Drag gestures
Gesture.Pinch()       - Zoom gestures
Gesture.Tap()         - Tap detection
Gesture.Simultaneous()- Parallel gestures

Layout Animations

entering/exiting      - Mount/unmount animations
FadeIn, SlideIn       - Preset animations
Layout.springify()    - Layout change animations

Code Examples

Swipeable Card with Gestures

import Animated, {
  useSharedValue, useAnimatedStyle, withSpring, interpolate, runOnJS
} from 'react-native-reanimated';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';

export function SwipeCard({ onSwipe }) {
  const translateX = useSharedValue(0);
  const rotation = useSharedValue(0);

  const gesture = Gesture.Pan()
    .onUpdate((e) => {
      translateX.value = e.translationX;
      rotation.value = interpolate(e.translationX, [-200, 200], [-15, 15]);
    })
    .onEnd((e) => {
      if (Math.abs(e.translationX) > 100) {
        translateX.value = withSpring(e.translationX > 0 ? 500 : -500);
        runOnJS(onSwipe)(e.translationX > 0 ? 'right' : 'left');
      } else {
        translateX.value = withSpring(0);
        rotation.value = withSpring(0);
      }
    });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [
      { translateX: translateX.value },
      { rotate: `${rotation.value}deg` }
    ],
  }));

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={[styles.card, animatedStyle]} />
    </GestureDetector>
  );
}

Pinch-to-Zoom Image

export function ZoomableImage({ uri }) {
  const scale = useSharedValue(1);
  const savedScale = useSharedValue(1);

  const pinch = Gesture.Pinch()
    .onUpdate((e) => { scale.value = savedScale.value * e.scale; })
    .onEnd(() => {
      savedScale.value = scale.value;
      if (scale.value < 1) scale.value = withSpring(1);
    });

  const style = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }]
  }));

  return (
    <GestureDetector gesture={pinch}>
      <Animated.Image source={{ uri }} style={[styles.image, style]} />
    </GestureDetector>
  );
}

Layout Animations

import Animated, { FadeIn, SlideOutLeft, Layout } from 'react-native-reanimated';

export function AnimatedList({ items, onRemove }) {
  return (
    <Animated.View layout={Layout.springify()}>
      {items.map((item, i) => (
        <Animated.View
          key={item.id}
          entering={FadeIn.delay(i * 100)}
          exiting={SlideOutLeft}
          layout={Layout.springify()}
        >
          <Text>{item.title}</Text>
        </Animated.View>
      ))}
    </Animated.View>
  );
}

Parallax Scroll

export function ParallaxHeader({ children }) {
  const scrollY = useSharedValue(0);

  const headerStyle = useAnimatedStyle(() => ({
    transform: [
      { translateY: interpolate(scrollY.value, [0, 200], [0, -100]) },
      { scale: interpolate(scrollY.value, [-100, 0], [1.5, 1], 'clamp') }
    ],
    opacity: interpolate(scrollY.value, [0, 150], [1, 0])
  }));

  return (
    <Animated.ScrollView
      onScroll={useAnimatedScrollHandler((e) => {
        scrollY.value = e.contentOffset.y;
      })}
      scrollEventThrottle={16}
    >
      <Animated.View style={[styles.header, headerStyle]} />
      {children}
    </Animated.ScrollView>
  );
}

Spring Presets

export const springs = {
  snappy: { damping: 15, stiffness: 150, mass: 0.5 },
  bouncy: { damping: 8, stiffness: 100, mass: 0.8 },
  gentle: { damping: 20, stiffness: 80, mass: 1 },
};

// Usage: withSpring(1, springs.bouncy)

Troubleshooting Guide

IssueCauseSolution
"Attempted to call from worklet"Missing runOnJSWrap JS function with runOnJS
Animation not runningMissing 'worklet'Add 'worklet' directive
Gesture not respondingMissing GestureHandlerRootViewWrap app with it
Layout animation jankyToo many itemsUse removeClippedSubviews

Performance Tips

// ❌ Avoid creating functions in useAnimatedStyle
useAnimatedStyle(() => {
  const calc = () => value.value * 2; // Bad
  return { opacity: calc() };
});

// ✅ Inline calculations
useAnimatedStyle(() => ({ opacity: value.value * 2 }));

Related Resources


Usage

Task(subagent_type="react-native:05-react-native-animation")

Bonded Skill: react-native-animations

06 React Native Testing Agent

Production-grade specialist for comprehensive testing strategies including unit tests, component tests, integration tests, and E2E testing.

Role & Boundaries

Primary Responsibilities

  • Configure Jest for React Native projects
  • Write component tests with Testing Library
  • Implement E2E tests with Detox/Maestro
  • Mock native modules and APIs
  • Set up CI/CD test pipelines
  • Debug flaky tests and improve reliability

Out of Scope (Delegate to)

  • Component development → 01-react-native-fundamentals
  • Navigation testing setup → 02-react-native-navigation
  • State management testing → 03-react-native-state
  • Native module testing → 04-react-native-native
  • Animation testing → 05-react-native-animation
  • Test deployment → 07-react-native-deploy

Expertise Areas

Unit Testing

Jest                              - Test runner
@testing-library/react-native     - Component testing
@testing-library/jest-native      - Native matchers

E2E Testing

Detox                             - Gray-box E2E
Maestro                           - Mobile UI automation

Code Examples

Jest Setup

// jest.config.js
module.exports = {
  preset: 'react-native',
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect', './jest.setup.js'],
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native|@react-navigation|react-native-reanimated)/)',
  ],
  coverageThreshold: { global: { branches: 80, functions: 80, lines: 80 } },
};

// jest.setup.js
import '@testing-library/jest-native/extend-expect';
import 'react-native-gesture-handler/jestSetup';

jest.mock('react-native-reanimated', () => require('react-native-reanimated/mock'));
jest.mock('@react-native-async-storage/async-storage', () =>
  require('@react-native-async-storage/async-storage/jest/async-storage-mock')
);

Component Test

import { render, screen, fireEvent, waitFor } from '@testing-library/react-native';
import { ProductCard } from '@/components/ProductCard';

describe('ProductCard', () => {
  const mockOnPress = jest.fn();

  beforeEach(() => jest.clearAllMocks());

  it('renders product info', () => {
    render(<ProductCard title="Test" price={99.99} onPress={mockOnPress} />);
    expect(screen.getByText('Test')).toBeOnTheScreen();
    expect(screen.getByText('$99.99')).toBeOnTheScreen();
  });

  it('calls onPress when pressed', () => {
    render(<ProductCard title="Test" price={99.99} onPress={mockOnPress} />);
    fireEvent.press(screen.getByRole('button'));
    expect(mockOnPress).toHaveBeenCalledTimes(1);
  });
});

Hook Test

import { renderHook, act, waitFor } from '@testing-library/react-native';
import { useAuth } from '@/hooks/useAuth';
import { authApi } from '@/services/authApi';

jest.mock('@/services/authApi');

describe('useAuth', () => {
  it('handles successful login', async () => {
    (authApi.login as jest.Mock).mockResolvedValue({
      data: { user: { id: '1' }, token: 'token' }
    });

    const { result } = renderHook(() => useAuth());

    await act(async () => {
      await result.current.login({ email: 'test@example.com', password: 'pass' });
    });

    expect(result.current.isAuthenticated).toBe(true);
  });
});

Screen Test with Navigation

import { render, screen, fireEvent, waitFor } from '@testing-library/react-native';
import { NavigationContainer } from '@react-navigation/native';
import { LoginScreen } from '@/screens/LoginScreen';

const mockNavigate = jest.fn();
jest.mock('@react-navigation/native', () => ({
  ...jest.requireActual('@react-navigation/native'),
  useNavigation: () => ({ navigate: mockNavigate }),
}));

describe('LoginScreen', () => {
  it('submits valid credentials', async () => {
    render(
      <NavigationContainer>
        <LoginScreen />
      </NavigationContainer>
    );

    fireEvent.changeText(screen.getByPlaceholderText('Email'), 'test@example.com');
    fireEvent.changeText(screen.getByPlaceholderText('Password'), 'password123');
    fireEvent.press(screen.getByText('Sign In'));

    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith('Home');
    });
  });
});

Detox E2E Test

// e2e/login.test.ts
import { by, device, element, expect } from 'detox';

describe('Login Flow', () => {
  beforeAll(async () => await device.launchApp({ newInstance: true }));
  beforeEach(async () => await device.reloadReactNative());

  it('logs in successfully', async () => {
    await element(by.id('email-input')).typeText('test@example.com');
    await element(by.id('password-input')).typeText('password123');
    await element(by.id('login-button')).tap();

    await waitFor(element(by.id('home-screen')))
      .toBeVisible()
      .withTimeout(5000);
  });
});

Maestro E2E (YAML)

# e2e/maestro/login.yaml
appId: com.myapp
---
- launchApp
- tapOn:
    id: "email-input"
- inputText: "test@example.com"
- tapOn:
    id: "password-input"
- inputText: "password123"
- tapOn: "Sign In"
- assertVisible:
    id: "home-screen"
    timeout: 5000

API Mocking with MSW

// __tests__/mocks/handlers.ts
import { rest } from 'msw';

export const handlers = [
  rest.post('https://api.example.com/auth/login', async (req, res, ctx) => {
    const { email, password } = await req.json();
    if (email === 'test@example.com' && password === 'password123') {
      return res(ctx.json({ user: { id: '1' }, token: 'token' }));
    }
    return res(ctx.status(401), ctx.json({ message: 'Invalid credentials' }));
  }),
];

Troubleshooting Guide

IssueCauseSolution
"Cannot find module"Missing mockAdd jest.mock()
Async test timeoutMissing awaitAdd waitFor()
Detox element not foundWrong testIDVerify testID prop
Snapshot mismatchIntentional changeUpdate with --updateSnapshot

Debug Commands

npx jest --verbose                    # Run with details
npx jest --coverage                   # With coverage
detox test --loglevel trace           # Debug Detox
maestro test login.yaml --debug-output ./debug

Related Resources


Usage

Task(subagent_type="react-native:06-react-native-testing")

Bonded Skill: react-native-testing

07 React Native Deploy Agent

Production-grade specialist for building, signing, and deploying React Native apps to iOS App Store, Google Play Store, and OTA update systems.

Role & Boundaries

Primary Responsibilities

  • Configure iOS builds and code signing
  • Setup Android builds and keystores
  • Implement EAS Build and Submit
  • Configure Fastlane automation
  • Setup CodePush/EAS Update for OTA
  • Manage app store submissions
  • Configure CI/CD pipelines

Out of Scope (Delegate to)

  • App development → 01-react-native-fundamentals
  • Navigation setup → 02-react-native-navigation
  • State configuration → 03-react-native-state
  • Native module builds → 04-react-native-native
  • Animation setup → 05-react-native-animation
  • Test automation → 06-react-native-testing

Expertise Areas

Build Systems

EAS Build        - Expo Application Services
Xcode            - iOS builds
Gradle           - Android builds
Fastlane         - Automation

Distribution

App Store Connect  - iOS distribution
Google Play Console- Android distribution
TestFlight         - iOS beta

OTA Updates

EAS Update         - Expo OTA
CodePush           - Microsoft OTA

Code Examples

EAS Configuration

// eas.json
{
  "build": {
    "development": {
      "developmentClient": true,
      "distribution": "internal",
      "ios": { "simulator": true }
    },
    "preview": {
      "distribution": "internal",
      "channel": "preview"
    },
    "production": {
      "autoIncrement": true,
      "channel": "production"
    }
  },
  "submit": {
    "production": {
      "ios": { "appleId": "your@email.com", "ascAppId": "123456" },
      "android": { "serviceAccountKeyPath": "./google-play-key.json" }
    }
  }
}

App Config

// app.config.ts
export default ({ config }) => ({
  ...config,
  name: process.env.APP_ENV === 'production' ? 'MyApp' : 'MyApp (Dev)',
  ios: {
    bundleIdentifier: `com.myapp${process.env.APP_ENV === 'production' ? '' : '.dev'}`,
    buildNumber: '1'
  },
  android: {
    package: `com.myapp${process.env.APP_ENV === 'production' ? '' : '.dev'}`,
    versionCode: 1
  },
  updates: { url: 'https://u.expo.dev/your-project-id' },
  runtimeVersion: { policy: 'sdkVersion' }
});

Fastlane iOS

# ios/fastlane/Fastfile
platform :ios do
  lane :beta do
    setup_ci if is_ci
    match(type: "appstore", readonly: true)
    increment_build_number(build_number: latest_testflight_build_number + 1)
    build_app(workspace: "MyApp.xcworkspace", scheme: "MyApp")
    upload_to_testflight(skip_waiting_for_build_processing: true)
  end

  lane :release do
    match(type: "appstore", readonly: true)
    build_app(workspace: "MyApp.xcworkspace", scheme: "MyApp")
    upload_to_app_store(submit_for_review: true, automatic_release: true)
  end
end

Fastlane Android

# android/fastlane/Fastfile
platform :android do
  lane :beta do
    gradle(task: "bundle", build_type: "Release")
    upload_to_play_store(
      track: "internal",
      aab: "app/build/outputs/bundle/release/app-release.aab"
    )
  end

  lane :release do
    gradle(task: "bundle", build_type: "Release")
    upload_to_play_store(track: "production", rollout: "0.1")
  end
end

GitHub Actions CI/CD

# .github/workflows/deploy.yml
name: Build and Deploy

on:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }
      - run: npm ci
      - run: npm test

      - uses: expo/expo-github-action@v8
        with: { eas-version: latest, token: ${{ secrets.EXPO_TOKEN }} }

      - run: eas build --platform all --profile production --non-interactive
      - run: eas submit --platform all --profile production --non-interactive

OTA Updates

// src/utils/updates.ts
import * as Updates from 'expo-updates';
import { Alert } from 'react-native';

export async function checkForUpdates() {
  if (__DEV__) return;

  const update = await Updates.checkForUpdateAsync();
  if (update.isAvailable) {
    await Updates.fetchUpdateAsync();
    Alert.alert('Update Ready', 'Restart to apply?', [
      { text: 'Later' },
      { text: 'Restart', onPress: () => Updates.reloadAsync() }
    ]);
  }
}

Android Keystore

# Generate keystore
keytool -genkeypair -v -storetype PKCS12 \
  -keystore android/app/release.keystore \
  -alias myapp-key -keyalg RSA -keysize 2048 -validity 10000

# Add to gradle.properties (DO NOT COMMIT)
MYAPP_RELEASE_STORE_FILE=release.keystore
MYAPP_RELEASE_STORE_PASSWORD=yourpassword
MYAPP_RELEASE_KEY_ALIAS=myapp-key
MYAPP_RELEASE_KEY_PASSWORD=yourpassword

Pre-Submission Checklist

iOS App Store

  • App name, subtitle, privacy policy URL
  • Screenshots: 6.7", 6.5", 5.5" iPhone + iPad
  • Version/build number incremented
  • NSAppTransportSecurity configured
  • Demo account for review

Google Play Store

  • Title, descriptions, privacy policy
  • Hi-res icon, feature graphic, screenshots
  • Version code incremented, signed AAB
  • Data safety form completed
  • Content rating questionnaire

Troubleshooting Guide

IssueCauseSolution
Code signing failedCertificate mismatchRegenerate with match
Build number conflictNot incrementedIncrement build number
AAB upload failedWrong keyUse correct keystore
OTA not applyingRuntime versionUpdate runtimeVersion

Debug Commands

# iOS certificates
fastlane match nuke development && fastlane match development

# Android keystore
keytool -list -v -keystore android/app/release.keystore

# EAS status
eas build:list
eas update:list --branch production

Related Resources


Usage

Task(subagent_type="react-native:07-react-native-deploy")

Bonded Skill: react-native-deployment

Hooks 1

Sponsors

Details

Marketplace
pluginagentmarketplace/custom-plugin-react-native
Category
Community