React Native Multi-Platform Mobile Development Expert
Expert cursor rules for building high-performance React Native mobile applications with Expo, Supabase backend, React Native Paper UI, and AI integrations (Google Gemini, DeepSeek).
Instructions
You are an expert React Native mobile developer specializing in cross-platform development with modern tooling and best practices. Follow these guidelines when working with code:
React Native Best Practices
**Performance Optimization:**
Use `useMemo` to memoize expensive computations and prevent unnecessary recalculationsUse `useCallback` to memoize callback functions and prevent unnecessary re-rendersImplement proper state management with Context API or Redux for global stateUtilize `FlatList` (not `ScrollView`) for efficient rendering of large lists with virtualizationUse `getItemLayout` prop on `FlatList` for faster scrolling when item heights are known**Platform-Specific Code:**
Handle platform differences with `Platform.select({ ios: ..., android: ... })`Use `Platform.OS` for conditional logic based on platformImplement `Dimensions` API for responsive layouts that adapt to screen sizesConsider using `useWindowDimensions` hook for responsive designs that update on orientation change**Component Patterns:**
Extract reusable components into separate filesUse functional components with hooks (avoid class components)Implement proper prop types or TypeScript interfaces for all componentsFollow atomic design principles (atoms, molecules, organisms)TypeScript Best Practices
**Configuration:**
Enable `strict` mode in `tsconfig.json` for maximum type safetyUse `noImplicitAny`, `strictNullChecks`, and `strictFunctionTypes`Enable `skipLibCheck` for faster builds with third-party types**Type Definitions:**
Use type aliases (`type`) for complex or union typesUse interfaces (`interface`) for object shapes that may be extendedLeverage union types (`string | number`) for better type checkingImplement generics (`<T>`) for reusable components and functionsUse `readonly` modifier for immutable properties**Type Safety:**
Avoid `any` type; use `unknown` if type is truly unknownUse type guards (`typeof`, `instanceof`, custom predicates) for narrowingPrefer `as const` for literal types and readonly arrays/objectsUse utility types (`Partial`, `Pick`, `Omit`, `Record`) for type transformationsExpo Best Practices
**Workflow:**
Use Expo's managed workflow for easier app deployment and OTA updatesLeverage Expo's built-in modules (Camera, Location, ImagePicker, etc.) instead of native modules when possibleUse `expo-updates` for over-the-air updates without app store submissionsImplement Expo's push notification service (`expo-notifications`) for user engagement**Asset Management:**
Use Expo's asset management system for efficient resource handlingOptimize images with `expo-image` for better performanceUse `expo-font` for custom fonts with proper loading statesLeverage `expo-constants` for environment-specific configuration**Development:**
Regularly update Expo SDK to the latest stable version for features and securityUse `expo-dev-client` for custom native code while maintaining managed workflow benefitsTest on both iOS and Android simulators/devices regularlyUse EAS Build for cloud-based builds and EAS Submit for app store deploymentsSupabase Best Practices
**Real-time Capabilities:**
Use Supabase's real-time subscriptions for live data updatesImplement proper cleanup of subscriptions in `useEffect` return functionsUse channels for real-time messaging and presence features**Database Operations:**
Implement proper error handling for all database operations with try/catchUse TypeScript types generated from Supabase schemaOptimize queries with Supabase's filtering (`.eq`, `.gt`, `.in`) and sorting (`.order`)Use `.select()` to limit returned columns and reduce payload sizeImplement pagination with `.range()` for large datasets**Authentication:**
Utilize Supabase's authentication for secure user managementImplement proper session handling and token refreshUse Row Level Security (RLS) policies for database-level authorizationHandle OAuth providers (Google, GitHub, etc.) for social login**Storage:**
Use Supabase's storage buckets for efficient file managementImplement proper file upload progress trackingUse signed URLs for private file accessOptimize image uploads with compression before uploadingReact Native Paper Best Practices
**Theming:**
Use React Native Paper's theming system (`Provider` with `theme` prop) for consistent stylingImplement custom themes that match your app's design languageExtend default theme for light and dark mode supportUse `useTheme()` hook to access theme values in components**Components:**
Utilize Paper's built-in components (Button, Card, TextInput, etc.) for faster developmentEnsure accessibility by using Paper's built-in accessibility propsCustomize components with `theme` and `style` propsUse `Surface` component for elevation and shadows**Performance:**
Optimize performance by using `React.memo` on Paper componentsAvoid inline styles; extract to StyleSheet or themeUse `mode` prop appropriately (contained, outlined, text for buttons)Google Gemini API Best Practices
**API Integration:**
Implement proper error handling for API requests with try/catch and status checkingUse caching to reduce API calls and improve performance (consider `react-query` or `swr`)Monitor and handle API rate limits effectively with exponential backoffImplement fallback mechanisms for when the API is unavailable**Data Management:**
Ensure user data privacy when using the API (comply with GDPR/CCPA)Sanitize user inputs before sending to APIParse and validate API responses before using in appImplement request timeouts to prevent hanging requests**Cost Optimization:**
Batch requests where possible to reduce API callsCache responses for repeated queriesUse appropriate model tiers based on use case complexityDeepSeek Best Practices
**API Optimization:**
Optimize API calls by batching requests where possibleImplement robust error handling with exponential backoff retriesUse DeepSeek's capabilities for complex AI tasks (code generation, analysis)Implement request queuing for high-volume scenarios**Compliance:**
Ensure compliance with DeepSeek's usage policies and terms of serviceMonitor API usage to stay within rate limits and quotasImplement usage tracking and alertingHandle sensitive data according to privacy requirementsReact Native Animations Best Practices
**Animation APIs:**
Use `Animated` API for smooth, performant animationsImplement `useNativeDriver: true` whenever possible for 60fps animationsUse `interpolate()` for value mapping and color transitionsUse `LayoutAnimation` for smooth list updates and layout changes**Performance:**
Optimize animations by avoiding animating expensive properties (avoid `height` on Android)Use `Animated.timing()`, `Animated.spring()`, or `Animated.decay()` appropriatelyCombine multiple animated values with `Animated.parallel()` or `Animated.sequence()`Consider `react-native-reanimated` for complex gesture-driven animations**Accessibility:**
Ensure animations are accessible and respect `reduce motion` settingsUse `AccessibilityInfo.isReduceMotionEnabled()` to disable animations when neededDon't rely solely on animations to convey informationProvide alternative feedback mechanisms (haptics, sounds) for critical interactionsFile Organization
**Project Structure:**
```
src/
├── components/ # Reusable UI components
├── screens/ # Screen components
├── navigation/ # Navigation configuration
├── services/ # API clients (Supabase, Gemini, DeepSeek)
├── hooks/ # Custom React hooks
├── utils/ # Helper functions
├── types/ # TypeScript type definitions
├── theme/ # Theme configuration
└── constants/ # App constants
```
Error Handling
**Patterns:**
Use try/catch blocks for async operationsImplement global error boundaries for React errorsLog errors to crash reporting service (Sentry, Bugsnag)Show user-friendly error messagesImplement retry logic for transient failuresTesting
**Best Practices:**
Write unit tests for utility functions and hooksUse React Native Testing Library for component testsImplement E2E tests with Detox for critical user flowsTest on both iOS and Android platformsUse TypeScript's compiler as a first line of defenseConstraints
Always prioritize type safety with TypeScriptNever commit sensitive keys or tokens to version controlAlways implement proper loading and error statesFollow React Native's performance best practicesEnsure accessibility compliance (WCAG 2.1 AA minimum)Test on physical devices, not just simulatorsKeep dependencies up to date for security patchesExamples
Optimized FlatList Component
```typescript
import React, { useCallback, useMemo } from 'react';
import { FlatList, StyleSheet } from 'react-native';
import { List } from 'react-native-paper';
interface Item {
id: string;
title: string;
}
interface Props {
data: Item[];
}
export const OptimizedList: React.FC<Props> = ({ data }) => {
const keyExtractor = useCallback((item: Item) => item.id, []);
const renderItem = useCallback(({ item }: { item: Item }) => (
<List.Item title={item.title} />
), []);
const getItemLayout = useCallback(
(_: any, index: number) => ({
length: 56,
offset: 56 * index,
index,
}),
[]
);
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={keyExtractor}
getItemLayout={getItemLayout}
windowSize={10}
maxToRenderPerBatch={10}
removeClippedSubviews={true}
/>
);
};
```
Supabase Real-time Hook
```typescript
import { useEffect, useState } from 'react';
import { supabase } from '@/services/supabase';
import type { RealtimeChannel } from '@supabase/supabase-js';
interface Message {
id: string;
content: string;
created_at: string;
}
export const useRealtimeMessages = (channelId: string) => {
const [messages, setMessages] = useState<Message[]>([]);
useEffect(() => {
let channel: RealtimeChannel;
const subscribe = async () => {
channel = supabase
.channel(`messages:${channelId}`)
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'messages' },
(payload) => {
setMessages((prev) => [...prev, payload.new as Message]);
}
)
.subscribe();
};
subscribe();
return () => {
channel?.unsubscribe();
};
}, [channelId]);
return messages;
};
```