Building cross-platform mobile apps with React Native including navigation, state management, and native modules
# React Native Mobile Development for Google Antigravity
Build cross-platform mobile apps with React Native using Google Antigravity's Gemini 3 engine. This guide covers navigation, state management, native modules, and performance optimization.
## Navigation Setup
```typescript
// src/navigation/RootNavigator.tsx
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 { HomeScreen } from '@/screens/HomeScreen';
import { ProfileScreen } from '@/screens/ProfileScreen';
import { SettingsScreen } from '@/screens/SettingsScreen';
import { LoginScreen } from '@/screens/LoginScreen';
import { SignupScreen } from '@/screens/SignupScreen';
import { ProductDetailScreen } from '@/screens/ProductDetailScreen';
import { Icon } from '@/components/Icon';
export type RootStackParamList = {
Auth: undefined;
Main: undefined;
ProductDetail: { productId: string };
};
export type AuthStackParamList = {
Login: undefined;
Signup: undefined;
};
export type MainTabParamList = {
Home: undefined;
Profile: undefined;
Settings: undefined;
};
const RootStack = createNativeStackNavigator<RootStackParamList>();
const AuthStack = createNativeStackNavigator<AuthStackParamList>();
const MainTab = createBottomTabNavigator<MainTabParamList>();
function AuthNavigator() {
return (
<AuthStack.Navigator screenOptions={{ headerShown: false }}>
<AuthStack.Screen name="Login" component={LoginScreen} />
<AuthStack.Screen name="Signup" component={SignupScreen} />
</AuthStack.Navigator>
);
}
function MainNavigator() {
return (
<MainTab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName: string;
switch (route.name) {
case 'Home':
iconName = focused ? 'home' : 'home-outline';
break;
case 'Profile':
iconName = focused ? 'person' : 'person-outline';
break;
case 'Settings':
iconName = focused ? 'settings' : 'settings-outline';
break;
default:
iconName = 'help';
}
return <Icon name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: '#007AFF',
tabBarInactiveTintColor: 'gray',
})}
>
<MainTab.Screen name="Home" component={HomeScreen} />
<MainTab.Screen name="Profile" component={ProfileScreen} />
<MainTab.Screen name="Settings" component={SettingsScreen} />
</MainTab.Navigator>
);
}
export function RootNavigator() {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <SplashScreen />;
}
return (
<NavigationContainer>
<RootStack.Navigator screenOptions={{ headerShown: false }}>
{isAuthenticated ? (
<>
<RootStack.Screen name="Main" component={MainNavigator} />
<RootStack.Screen
name="ProductDetail"
component={ProductDetailScreen}
options={{ headerShown: true, title: 'Product' }}
/>
</>
) : (
<RootStack.Screen name="Auth" component={AuthNavigator} />
)}
</RootStack.Navigator>
</NavigationContainer>
);
}
```
## State Management with Zustand
```typescript
// src/stores/authStore.ts
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { api } from '@/services/api';
interface User {
id: string;
email: string;
name: string;
avatar?: string;
}
interface AuthState {
user: User | null;
token: string | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
signup: (email: string, password: string, name: string) => Promise<void>;
logout: () => void;
refreshToken: () => Promise<void>;
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
user: null,
token: null,
isLoading: false,
login: async (email, password) => {
set({ isLoading: true });
try {
const { user, token } = await api.auth.login(email, password);
set({ user, token, isLoading: false });
} catch (error) {
set({ isLoading: false });
throw error;
}
},
signup: async (email, password, name) => {
set({ isLoading: true });
try {
const { user, token } = await api.auth.signup(email, password, name);
set({ user, token, isLoading: false });
} catch (error) {
set({ isLoading: false });
throw error;
}
},
logout: () => {
set({ user: null, token: null });
},
refreshToken: async () => {
const { token } = get();
if (!token) return;
try {
const { token: newToken } = await api.auth.refresh(token);
set({ token: newToken });
} catch {
get().logout();
}
},
}),
{
name: 'auth-storage',
storage: createJSONStorage(() => AsyncStorage),
partialize: (state) => ({ user: state.user, token: state.token }),
}
)
);
```
## Custom Hooks
```typescript
// src/hooks/useApi.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/services/api';
export function useProducts(filters?: { category?: string }) {
return useQuery({
queryKey: ['products', filters],
queryFn: () => api.products.list(filters),
});
}
export function useProduct(id: string) {
return useQuery({
queryKey: ['product', id],
queryFn: () => api.products.getById(id),
enabled: !!id,
});
}
export function useAddToCart() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { productId: string; quantity: number }) =>
api.cart.addItem(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['cart'] });
},
});
}
// src/hooks/usePushNotifications.ts
import { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { PermissionsAndroid, Platform } from 'react-native';
export function usePushNotifications() {
useEffect(() => {
async function requestPermission() {
if (Platform.OS === 'android') {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
}
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
const token = await messaging().getToken();
console.log('FCM Token:', token);
// Send token to backend
}
}
requestPermission();
// Handle foreground messages
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
console.log('Foreground message:', remoteMessage);
// Show local notification
});
return unsubscribe;
}, []);
}
```
## Optimized List Component
```typescript
// src/components/ProductList.tsx
import { memo, useCallback } from 'react';
import {
FlatList,
RefreshControl,
ActivityIndicator,
View,
Text,
StyleSheet,
} from 'react-native';
import { ProductCard } from './ProductCard';
import { useProducts } from '@/hooks/useApi';
interface Product {
id: string;
name: string;
price: number;
image: string;
}
export const ProductList = memo(function ProductList() {
const {
data,
isLoading,
isRefetching,
refetch,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useProducts();
const products = data?.pages.flatMap((page) => page.items) ?? [];
const renderItem = useCallback(
({ item }: { item: Product }) => <ProductCard product={item} />,
[]
);
const keyExtractor = useCallback((item: Product) => item.id, []);
const onEndReached = useCallback(() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
const ListFooter = useCallback(() => {
if (!isFetchingNextPage) return null;
return (
<View style={styles.footer}>
<ActivityIndicator />
</View>
);
}, [isFetchingNextPage]);
const ListEmpty = useCallback(() => {
if (isLoading) return null;
return (
<View style={styles.empty}>
<Text>No products found</Text>
</View>
);
}, [isLoading]);
if (isLoading) {
return (
<View style={styles.loading}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<FlatList
data={products}
renderItem={renderItem}
keyExtractor={keyExtractor}
numColumns={2}
columnWrapperStyle={styles.row}
contentContainerStyle={styles.container}
refreshControl={
<RefreshControl refreshing={isRefetching} onRefresh={refetch} />
}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
ListFooterComponent={ListFooter}
ListEmptyComponent={ListEmpty}
removeClippedSubviews={true}
maxToRenderPerBatch={10}
windowSize={5}
/>
);
});
const styles = StyleSheet.create({
container: { padding: 8 },
row: { justifyContent: 'space-between' },
loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
footer: { padding: 16, alignItems: 'center' },
empty: { flex: 1, justifyContent: 'center', alignItems: 'center' },
});
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these React Native patterns: Use FlatList with proper optimization props. Implement offline-first with AsyncStorage. Add deep linking for better UX. Use native navigation for performance. Implement proper error boundaries.This React Native prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their react native implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For React Native projects, consider mentioning your framework version, coding style, and any specific libraries you're using.