React Native Multi-Stack Best Practices
Comprehensive development guidelines for React Native projects using Expo, Supabase, React Native Paper, TypeScript, and AI integrations.
Instructions
When working on React Native projects matching the file patterns below, apply these best practices to ensure optimal performance, maintainability, and user experience.
React Native Core Practices
**Performance Optimization:**
Use `useMemo` and `useCallback` to prevent unnecessary re-rendersImplement proper state management with Context API or ReduxUtilize `FlatList` for efficient rendering of large lists (virtualization)Profile components with React DevTools to identify bottlenecks**Platform-Specific Code:**
Handle platform differences with `Platform.select` for conditional logicUse `Dimensions` API for responsive layouts across devicesTest on both iOS and Android platforms regularlyTypeScript Standards
**Type Safety Configuration:**
Enable `strict` mode in `tsconfig.json` for maximum type safetyUse type aliases for complex or reusable typesLeverage union types (`type Status = 'pending' | 'complete'`) for better type checkingImplement generics for reusable, type-safe components and functionsUse `readonly` modifier for immutable propertiesAvoid `any` type; use `unknown` when type is truly unknown**Example:**
```typescript
type User = {
readonly id: string;
name: string;
status: 'active' | 'inactive';
};
function fetchData<T>(url: string): Promise<T> {
// Generic function implementation
}
```
Expo Best Practices
**Workflow & Deployment:**
Use Expo's managed workflow for simplified deployment and OTA updatesLeverage Expo's built-in modules (Camera, Location, Notifications) instead of native modules when possibleImplement Expo's push notification service for cross-platform notificationsUse Expo's asset management system for efficient bundling of images, fonts, and other resourcesKeep Expo SDK updated to latest stable version for security and features**Configuration:**
Configure `app.json` or `app.config.js` properly for both iOS and AndroidUse EAS Build for production-grade native buildsSupabase Backend Integration
**Database Operations:**
Use Supabase's real-time subscriptions for live data updatesImplement proper error handling with try-catch blocks for all database operationsUtilize Supabase's Row Level Security (RLS) policies for data access controlOptimize queries using filtering (`.eq()`, `.in()`) and sorting (`.order()`) methodsUse Supabase Storage for efficient file management (avatars, documents)**Authentication:**
Implement Supabase Auth for secure user management (email, OAuth, magic links)Store session tokens securely using `AsyncStorage` or `SecureStore`Handle auth state changes with `onAuthStateChange` listener**Example:**
```typescript
const { data, error } = await supabase
.from('users')
.select('*')
.eq('status', 'active')
.order('created_at', { ascending: false });
if (error) {
console.error('Database error:', error);
// Handle error appropriately
}
```
React Native Paper UI Components
**Theming & Styling:**
Use React Native Paper's theming system for consistent design across the appImplement custom themes by extending the default theme to match brand identityUtilize Paper's built-in components (Button, Card, TextInput) for faster developmentEnsure accessibility by using Paper's accessibility props (`accessibilityLabel`, `accessibilityHint`)Optimize performance by wrapping Paper components with `React.memo` when appropriate**Example:**
```typescript
import { Provider as PaperProvider, DefaultTheme } from 'react-native-paper';
const theme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primary: '#6200ee',
accent: '#03dac4',
},
};
<PaperProvider theme={theme}>
{/* Your app */}
</PaperProvider>
```
Google Gemini API Integration
**API Usage Best Practices:**
Implement proper error handling for all API requests with retries for transient failuresUse caching strategies (in-memory or persistent) to reduce redundant API callsMonitor and respect API rate limits; implement exponential backoffImplement fallback mechanisms (cached responses, graceful degradation) when API is unavailableEnsure user data privacy: sanitize inputs and don't send sensitive data to external APIs**Example:**
```typescript
try {
const response = await fetch('https://generativelanguage.googleapis.com/...', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt: sanitizedInput }),
});
if (!response.ok) throw new Error(`API error: ${response.status}`);
const data = await response.json();
// Cache the result
} catch (error) {
console.error('Gemini API error:', error);
// Use cached fallback or show user-friendly error
}
```
DeepSeek AI Integration
**Optimization & Reliability:**
Batch multiple requests where possible to reduce API overheadImplement robust error handling with retry logic (exponential backoff)Use DeepSeek's capabilities for complex reasoning, code generation, or multi-step tasksEnsure compliance with DeepSeek's usage policies and terms of serviceMonitor API usage via logs or analytics to stay within rate limits and budgetCache AI responses when appropriate to improve latency and reduce costsReact Native Animations
**Animation Performance:**
Use `Animated` API for declarative, performant animationsEnable `useNativeDriver: true` to offload animations to native thread (smoves 60fps)Use `interpolate` for value mapping and complex animation sequencesImplement `LayoutAnimation` for automatic layout transition animations (list updates, reordering)Ensure animations are accessible: provide `reducedMotion` support for users sensitive to motion**Example:**
```typescript
import { Animated, Easing } from 'react-native';
const fadeAnim = useRef(new Animated.Value(0)).current;
Animated.timing(fadeAnim, {
toValue: 1,
duration: 500,
easing: Easing.ease,
useNativeDriver: true, // Performance boost
}).start();
```
General Development Guidelines
**Code Organization:**
Structure components by feature, not by type (e.g., `/features/auth/`, not `/components/`, `/screens/`)Use absolute imports for cleaner import pathsSeparate business logic from UI components**Testing:**
Write unit tests for utility functions and custom hooksUse React Native Testing Library for component testsTest on both iOS and Android simulators/devices**Security:**
Store sensitive keys (API keys, secrets) in environment variables, never hardcodeUse Expo SecureStore for storing sensitive user data on deviceValidate and sanitize all user inputs before processing or sending to APIs**Performance:**
Use `React.memo`, `useMemo`, and `useCallback` to prevent unnecessary rendersLazy load screens and components with `React.lazy` and SuspenseProfile app with Flipper or React Native Performance MonitorFile Patterns
Apply these practices to files matching:
`**/*.ts``**/*.tsx``**/*.js``**/*.jsx`Notes
Adapt these guidelines to your project's specific file structure and requirementsRegularly review and update dependencies for security patchesFollow React Native's official documentation for platform-specific considerationsTest thoroughly on both iOS and Android before production releases