- React Native: Advanced Development Guide
React Native: Advanced Development Guide
React Native, developed by Meta (formerly Facebook), has revolutionized mobile application development by enabling engineers to build native mobile applications using JavaScript and React. This comprehensive guide explores advanced concepts, optimization techniques, and architectural patterns essential for production-grade React Native applications.
Environment Setup & Configuration
Optimizing Development Environment
The latest React Native versions (0.71+) require specific configurations for optimal performance:
- JDK Requirements: Migrate from Java 8 to JDK 11+ for improved build performance and compatibility
- Node.js Environment: Utilize Node.js v14+ with Yarn for dependency management
- Virtual Machine Configuration: Configure hardware acceleration and sufficient memory allocation
For macOS development environments, establish the following environment variables:
# Add to ~/.zshrc or ~/.bash_profile
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
# Optimize Metro bundler performance
export REACT_NATIVE_MAX_WORKERS=4
# Add to ~/.zshrc or ~/.bash_profile
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
# Optimize Metro bundler performance
export REACT_NATIVE_MAX_WORKERS=4
Project Initialization with TypeScript
Leverage TypeScript templates for type safety and improved developer experience:
# Initialize with TypeScript template
npx react-native init EnterpriseApp --template react-native-template-typescript
# Configuration for module resolution and path aliases
cd EnterpriseApp
yarn add --dev babel-plugin-module-resolver
# Initialize with TypeScript template
npx react-native init EnterpriseApp --template react-native-template-typescript
# Configuration for module resolution and path aliases
cd EnterpriseApp
yarn add --dev babel-plugin-module-resolver
Configure babel.config.js
for module aliasing:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@components': './src/components',
'@screens': './src/screens',
'@utils': './src/utils',
'@services': './src/services',
'@assets': './src/assets',
},
},
],
],
};
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@components': './src/components',
'@screens': './src/screens',
'@utils': './src/utils',
'@services': './src/services',
'@assets': './src/assets',
},
},
],
],
};
Advanced Styling System
React Native’s styling system differs significantly from web CSS, with distinct performance implications and architectural considerations.
Optimized Styling Approaches
The React Native styling paradigm leverages JavaScript objects with a more performant implementation:
import React, { useMemo } from 'react'
import type { StyleProp, TextStyle, ViewStyle } from 'react-native'
import { StyleSheet, Text, View } from 'react-native'
interface StyleDemoProps {
isActive?: boolean
variant?: 'primary' | 'secondary'
customStyles?: StyleProp<ViewStyle>
}
export default function StyleDemo({ isActive = false, variant = 'primary', customStyles }: StyleDemoProps) {
// Compute derived styles efficiently with useMemo
const computedTextStyles = useMemo(() => {
return [
styles.text,
variant === 'primary' ? styles.primaryText : styles.secondaryText,
isActive && styles.activeText,
] as StyleProp<TextStyle>
}, [isActive, variant])
return (
<View style={[styles.container, customStyles]}>
{/* Inline styles - use sparingly, only for dynamic values */}
<Text style={{ fontSize: 18, opacity: isActive ? 1 : 0.7 }}>
Dynamic Inline Styling
</Text>
{/* Computed styles with useMemo for optimal performance */}
<Text style={computedTextStyles}>
Optimized Style Composition
</Text>
{/* StyleSheet reference - most performant */}
<Text style={styles.title}>
Static StyleSheet Reference
</Text>
</View>
)
}
// StyleSheet.create performs optimization during app initialization
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
backgroundColor: '#f8f9fa',
},
title: {
fontSize: 24,
fontWeight: 'bold',
letterSpacing: 0.25,
marginVertical: 16,
color: '#212529',
},
text: {
fontSize: 16,
lineHeight: 24,
},
primaryText: {
color: '#0062cc',
},
secondaryText: {
color: '#5a6268',
},
activeText: {
fontWeight: '600',
},
})
import React, { useMemo } from 'react'
import type { StyleProp, TextStyle, ViewStyle } from 'react-native'
import { StyleSheet, Text, View } from 'react-native'
interface StyleDemoProps {
isActive?: boolean
variant?: 'primary' | 'secondary'
customStyles?: StyleProp<ViewStyle>
}
export default function StyleDemo({ isActive = false, variant = 'primary', customStyles }: StyleDemoProps) {
// Compute derived styles efficiently with useMemo
const computedTextStyles = useMemo(() => {
return [
styles.text,
variant === 'primary' ? styles.primaryText : styles.secondaryText,
isActive && styles.activeText,
] as StyleProp<TextStyle>
}, [isActive, variant])
return (
<View style={[styles.container, customStyles]}>
{/* Inline styles - use sparingly, only for dynamic values */}
<Text style={{ fontSize: 18, opacity: isActive ? 1 : 0.7 }}>
Dynamic Inline Styling
</Text>
{/* Computed styles with useMemo for optimal performance */}
<Text style={computedTextStyles}>
Optimized Style Composition
</Text>
{/* StyleSheet reference - most performant */}
<Text style={styles.title}>
Static StyleSheet Reference
</Text>
</View>
)
}
// StyleSheet.create performs optimization during app initialization
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
backgroundColor: '#f8f9fa',
},
title: {
fontSize: 24,
fontWeight: 'bold',
letterSpacing: 0.25,
marginVertical: 16,
color: '#212529',
},
text: {
fontSize: 16,
lineHeight: 24,
},
primaryText: {
color: '#0062cc',
},
secondaryText: {
color: '#5a6268',
},
activeText: {
fontWeight: '600',
},
})
Critical Style System Characteristics
- Non-inheritance Model: Unlike CSS, styles don’t cascade (with the exception of text components)
- Performance Implications: Recomposition of style arrays can impact render performance
- Style References: StyleSheet.create generates optimized style references that improve memory usage
- Platform-Specific Styling: Use
.ios.js
and.android.js
extensions for platform-specific styles
Flexbox Layout Engineering
React Native implements a customized version of Flexbox optimized for mobile interfaces:
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
export default function AdvancedFlexboxDemo() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Advanced Flexbox Layout</Text>
</View>
<View style={styles.content}>
<View style={styles.sidebar}>
{['Home', 'Profile', 'Settings', 'Help'].map((item, index) => (
<View key={index} style={styles.sidebarItem}>
<Text style={styles.sidebarText}>{item}</Text>
</View>
))}
</View>
<View style={styles.mainContent}>
<View style={styles.card}>
<Text style={styles.cardTitle}>Primary Content</Text>
<Text style={styles.cardText}>
Implementing complex layouts with Flexbox requires understanding
how flex properties interact with each other.
</Text>
</View>
<View style={styles.metrics}>
{[1, 2, 3].map(item => (
<View key={item} style={styles.metricItem}>
<Text style={styles.metricValue}>{item * 25}%</Text>
<Text style={styles.metricLabel}>Metric {item}</Text>
</View>
))}
</View>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f0f2f5',
},
header: {
height: 60,
backgroundColor: '#1a73e8',
justifyContent: 'center',
paddingHorizontal: 16,
},
headerText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
content: {
flex: 1,
flexDirection: 'row',
},
sidebar: {
width: 120,
backgroundColor: '#ffffff',
paddingVertical: 16,
},
sidebarItem: {
paddingVertical: 12,
paddingHorizontal: 16,
},
sidebarText: {
fontSize: 14,
color: '#202124',
},
mainContent: {
flex: 1,
padding: 16,
},
card: {
backgroundColor: '#ffffff',
borderRadius: 8,
padding: 16,
marginBottom: 16,
elevation: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.41,
},
cardTitle: {
fontSize: 16,
fontWeight: '600',
marginBottom: 8,
color: '#202124',
},
cardText: {
fontSize: 14,
lineHeight: 21,
color: '#5f6368',
},
metrics: {
flexDirection: 'row',
justifyContent: 'space-between',
},
metricItem: {
flex: 1,
backgroundColor: '#ffffff',
borderRadius: 8,
padding: 16,
alignItems: 'center',
marginHorizontal: 4,
elevation: 1,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 1,
},
metricValue: {
fontSize: 20,
fontWeight: 'bold',
color: '#1a73e8',
},
metricLabel: {
fontSize: 12,
color: '#5f6368',
marginTop: 4,
},
})
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
export default function AdvancedFlexboxDemo() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Advanced Flexbox Layout</Text>
</View>
<View style={styles.content}>
<View style={styles.sidebar}>
{['Home', 'Profile', 'Settings', 'Help'].map((item, index) => (
<View key={index} style={styles.sidebarItem}>
<Text style={styles.sidebarText}>{item}</Text>
</View>
))}
</View>
<View style={styles.mainContent}>
<View style={styles.card}>
<Text style={styles.cardTitle}>Primary Content</Text>
<Text style={styles.cardText}>
Implementing complex layouts with Flexbox requires understanding
how flex properties interact with each other.
</Text>
</View>
<View style={styles.metrics}>
{[1, 2, 3].map(item => (
<View key={item} style={styles.metricItem}>
<Text style={styles.metricValue}>{item * 25}%</Text>
<Text style={styles.metricLabel}>Metric {item}</Text>
</View>
))}
</View>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f0f2f5',
},
header: {
height: 60,
backgroundColor: '#1a73e8',
justifyContent: 'center',
paddingHorizontal: 16,
},
headerText: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
content: {
flex: 1,
flexDirection: 'row',
},
sidebar: {
width: 120,
backgroundColor: '#ffffff',
paddingVertical: 16,
},
sidebarItem: {
paddingVertical: 12,
paddingHorizontal: 16,
},
sidebarText: {
fontSize: 14,
color: '#202124',
},
mainContent: {
flex: 1,
padding: 16,
},
card: {
backgroundColor: '#ffffff',
borderRadius: 8,
padding: 16,
marginBottom: 16,
elevation: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.41,
},
cardTitle: {
fontSize: 16,
fontWeight: '600',
marginBottom: 8,
color: '#202124',
},
cardText: {
fontSize: 14,
lineHeight: 21,
color: '#5f6368',
},
metrics: {
flexDirection: 'row',
justifyContent: 'space-between',
},
metricItem: {
flex: 1,
backgroundColor: '#ffffff',
borderRadius: 8,
padding: 16,
alignItems: 'center',
marginHorizontal: 4,
elevation: 1,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 1,
},
metricValue: {
fontSize: 20,
fontWeight: 'bold',
color: '#1a73e8',
},
metricLabel: {
fontSize: 12,
color: '#5f6368',
marginTop: 4,
},
})
Flexbox Implementation Distinctions
- Default Flow Direction: Column-oriented (vertical) as opposed to web’s row-oriented layout
- Flex Numeric Values: Single numeric values represent proportional space distribution
- Implicit Container Configuration: All View components are Flexbox containers by default
Component Architecture & Composition
React Native’s component model enables sophisticated patterns for building maintainable applications:
Higher-Order Components (HOCs)
import type { ComponentType } from 'react'
import React from 'react'
import { ActivityIndicator, StyleSheet, View } from 'react-native'
interface WithLoadingProps {
isLoading: boolean
}
// Higher-Order Component for loading states
export function withLoading<P extends object>(
WrappedComponent: ComponentType<P>
): React.FC<P & WithLoadingProps> {
return ({ isLoading, ...props }: WithLoadingProps & P) => {
if (isLoading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0062cc" />
</View>
)
}
return <WrappedComponent {...(props as P)} />
}
}
const styles = StyleSheet.create({
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(255, 255, 255, 0.7)',
},
})
import type { ComponentType } from 'react'
import React from 'react'
import { ActivityIndicator, StyleSheet, View } from 'react-native'
interface WithLoadingProps {
isLoading: boolean
}
// Higher-Order Component for loading states
export function withLoading<P extends object>(
WrappedComponent: ComponentType<P>
): React.FC<P & WithLoadingProps> {
return ({ isLoading, ...props }: WithLoadingProps & P) => {
if (isLoading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0062cc" />
</View>
)
}
return <WrappedComponent {...(props as P)} />
}
}
const styles = StyleSheet.create({
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(255, 255, 255, 0.7)',
},
})
Custom Hooks for Business Logic
import { useCallback, useEffect, useState } from 'react'
interface UseAPIOptions<T> {
initialData?: T
onSuccess?: (data: T) => void
onError?: (error: Error) => void
}
export function useAPI<T>(
fetchFn: () => Promise<T>,
options: UseAPIOptions<T> = {}
) {
const [data, setData] = useState<T | undefined>(options.initialData)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
const fetchData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const result = await fetchFn()
setData(result)
if (options.onSuccess)
options.onSuccess(result)
}
catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
setError(error)
if (options.onError)
options.onError(error)
}
finally {
setLoading(false)
}
}, [fetchFn, options.onSuccess, options.onError])
useEffect(() => {
fetchData()
}, [fetchData])
return {
data,
loading,
error,
refetch: fetchData,
}
}
import { useCallback, useEffect, useState } from 'react'
interface UseAPIOptions<T> {
initialData?: T
onSuccess?: (data: T) => void
onError?: (error: Error) => void
}
export function useAPI<T>(
fetchFn: () => Promise<T>,
options: UseAPIOptions<T> = {}
) {
const [data, setData] = useState<T | undefined>(options.initialData)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
const fetchData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const result = await fetchFn()
setData(result)
if (options.onSuccess)
options.onSuccess(result)
}
catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
setError(error)
if (options.onError)
options.onError(error)
}
finally {
setLoading(false)
}
}, [fetchFn, options.onSuccess, options.onError])
useEffect(() => {
fetchData()
}, [fetchData])
return {
data,
loading,
error,
refetch: fetchData,
}
}
Responsive Design & Adaptive Layouts
Implementing sophisticated responsive designs requires thoughtful abstractions:
import type { ScaledSize } from 'react-native'
import { Dimensions, PixelRatio, Platform } from 'react-native'
import { useEffect, useState } from 'react'
// Screen dimensions information
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window')
// Base dimensions (design specifications)
const DESIGN_WIDTH = 375
const DESIGN_HEIGHT = 812
// Scale factors
const widthScaleFactor = SCREEN_WIDTH / DESIGN_WIDTH
const heightScaleFactor = SCREEN_HEIGHT / DESIGN_HEIGHT
// Responsive dimension utilities
export const scaleWidth = (size: number): number => size * widthScaleFactor
export const scaleHeight = (size: number): number => size * heightScaleFactor
export const scaleFont = (size: number): number => {
const scale = Math.min(widthScaleFactor, heightScaleFactor)
const newSize = size * scale
if (Platform.OS === 'ios')
return Math.round(PixelRatio.roundToNearestPixel(newSize))
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
}
// Breakpoints for responsive design
export const Breakpoints = {
SMALL: 360,
MEDIUM: 768,
LARGE: 1024,
}
// Device type detection
export const isTablet = (): boolean => {
const { width, height } = Dimensions.get('window')
const aspectRatio = height / width
return aspectRatio < 1.6 && width >= 600
}
// Screen orientation hook
export function useOrientation() {
const [orientation, setOrientation] = useState<'portrait' | 'landscape'>(
SCREEN_WIDTH < SCREEN_HEIGHT ? 'portrait' : 'landscape'
)
useEffect(() => {
const onChange = ({ window }: { window: ScaledSize }) => {
setOrientation(window.width < window.height ? 'portrait' : 'landscape')
}
const subscription = Dimensions.addEventListener('change', onChange)
return () => {
subscription.remove()
}
}, [])
return orientation
}
import type { ScaledSize } from 'react-native'
import { Dimensions, PixelRatio, Platform } from 'react-native'
import { useEffect, useState } from 'react'
// Screen dimensions information
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window')
// Base dimensions (design specifications)
const DESIGN_WIDTH = 375
const DESIGN_HEIGHT = 812
// Scale factors
const widthScaleFactor = SCREEN_WIDTH / DESIGN_WIDTH
const heightScaleFactor = SCREEN_HEIGHT / DESIGN_HEIGHT
// Responsive dimension utilities
export const scaleWidth = (size: number): number => size * widthScaleFactor
export const scaleHeight = (size: number): number => size * heightScaleFactor
export const scaleFont = (size: number): number => {
const scale = Math.min(widthScaleFactor, heightScaleFactor)
const newSize = size * scale
if (Platform.OS === 'ios')
return Math.round(PixelRatio.roundToNearestPixel(newSize))
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
}
// Breakpoints for responsive design
export const Breakpoints = {
SMALL: 360,
MEDIUM: 768,
LARGE: 1024,
}
// Device type detection
export const isTablet = (): boolean => {
const { width, height } = Dimensions.get('window')
const aspectRatio = height / width
return aspectRatio < 1.6 && width >= 600
}
// Screen orientation hook
export function useOrientation() {
const [orientation, setOrientation] = useState<'portrait' | 'landscape'>(
SCREEN_WIDTH < SCREEN_HEIGHT ? 'portrait' : 'landscape'
)
useEffect(() => {
const onChange = ({ window }: { window: ScaledSize }) => {
setOrientation(window.width < window.height ? 'portrait' : 'landscape')
}
const subscription = Dimensions.addEventListener('change', onChange)
return () => {
subscription.remove()
}
}, [])
return orientation
}
Performance Optimization Strategies
Delivering optimal performance requires a multifaceted approach:
Render Optimization
Component Memoization:
const MemoizedComponent = React.memo(({ prop1, prop2 }) => { // Component implementation }, (prevProps, nextProps) => { // Custom comparison function return prevProps.prop1 === nextProps.prop1 })
const MemoizedComponent = React.memo(({ prop1, prop2 }) => { // Component implementation }, (prevProps, nextProps) => { // Custom comparison function return prevProps.prop1 === nextProps.prop1 })
Callback Stabilization:
const stableCallback = useCallback(() => { // Implementation }, [/* dependencies */])
const stableCallback = useCallback(() => { // Implementation }, [/* dependencies */])
Derived Data Memoization:
const derivedData = useMemo(() => { return expensiveComputation(prop1, prop2) }, [prop1, prop2])
const derivedData = useMemo(() => { return expensiveComputation(prop1, prop2) }, [prop1, prop2])
List Rendering Performance
Optimize list rendering with specialized techniques:
import React, { useCallback } from 'react'
import { FlatList, StyleSheet, Text, View } from 'react-native'
interface Item {
id: string
title: string
description: string
}
interface OptimizedListProps {
data: Item[]
onItemPress: (item: Item) => void
}
export default function OptimizedList({ data, onItemPress }: OptimizedListProps) {
// Stable item renderer with inline component
const renderItem = useCallback(({ item }: { item: Item }) => (
<ItemComponent item={item} onPress={onItemPress} />
), [onItemPress])
// Stable key extractor
const keyExtractor = useCallback((item: Item) => item.id, [])
// Optimize list configuration
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={keyExtractor}
// Performance optimizations
removeClippedSubviews={true}
maxToRenderPerBatch={10}
updateCellsBatchingPeriod={50}
windowSize={5}
initialNumToRender={7}
// Appearance
contentContainerStyle={styles.listContent}
/>
)
}
// Memoized item component
const ItemComponent = React.memo(({
item,
onPress
}: {
item: Item
onPress: (item: Item) => void
}) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.description}>{item.description}</Text>
</View>
))
const styles = StyleSheet.create({
listContent: {
padding: 16,
},
item: {
backgroundColor: 'white',
padding: 20,
marginVertical: 8,
borderRadius: 8,
elevation: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.41,
},
title: {
fontSize: 16,
fontWeight: 'bold',
},
description: {
marginTop: 8,
fontSize: 14,
color: '#666',
},
})
import React, { useCallback } from 'react'
import { FlatList, StyleSheet, Text, View } from 'react-native'
interface Item {
id: string
title: string
description: string
}
interface OptimizedListProps {
data: Item[]
onItemPress: (item: Item) => void
}
export default function OptimizedList({ data, onItemPress }: OptimizedListProps) {
// Stable item renderer with inline component
const renderItem = useCallback(({ item }: { item: Item }) => (
<ItemComponent item={item} onPress={onItemPress} />
), [onItemPress])
// Stable key extractor
const keyExtractor = useCallback((item: Item) => item.id, [])
// Optimize list configuration
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={keyExtractor}
// Performance optimizations
removeClippedSubviews={true}
maxToRenderPerBatch={10}
updateCellsBatchingPeriod={50}
windowSize={5}
initialNumToRender={7}
// Appearance
contentContainerStyle={styles.listContent}
/>
)
}
// Memoized item component
const ItemComponent = React.memo(({
item,
onPress
}: {
item: Item
onPress: (item: Item) => void
}) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.description}>{item.description}</Text>
</View>
))
const styles = StyleSheet.create({
listContent: {
padding: 16,
},
item: {
backgroundColor: 'white',
padding: 20,
marginVertical: 8,
borderRadius: 8,
elevation: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 1.41,
},
title: {
fontSize: 16,
fontWeight: 'bold',
},
description: {
marginTop: 8,
fontSize: 14,
color: '#666',
},
})
Integration with Native Modules
Expanding React Native’s capabilities through native module integration:
// TypeScript interface for the native module
interface GeolocationModule {
getCurrentPosition(): Promise<{
latitude: number
longitude: number
accuracy: number
timestamp: number
}>
startWatchingPosition(options: {
enableHighAccuracy: boolean
distanceFilter: number
}): void
stopWatchingPosition(): void
}
// Usage in a custom hook
function useGeolocation() {
const [location, setLocation] = useState(null)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
const getLocation = async () => {
try {
// Accessing the native module
const geolocation = NativeModules.GeolocationModule as GeolocationModule
const position = await geolocation.getCurrentPosition()
setLocation(position)
}
catch (err) {
setError(err instanceof Error ? err : new Error(String(err)))
}
}
getLocation()
}, [])
return { location, error }
}
// TypeScript interface for the native module
interface GeolocationModule {
getCurrentPosition(): Promise<{
latitude: number
longitude: number
accuracy: number
timestamp: number
}>
startWatchingPosition(options: {
enableHighAccuracy: boolean
distanceFilter: number
}): void
stopWatchingPosition(): void
}
// Usage in a custom hook
function useGeolocation() {
const [location, setLocation] = useState(null)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
const getLocation = async () => {
try {
// Accessing the native module
const geolocation = NativeModules.GeolocationModule as GeolocationModule
const position = await geolocation.getCurrentPosition()
setLocation(position)
}
catch (err) {
setError(err instanceof Error ? err : new Error(String(err)))
}
}
getLocation()
}, [])
return { location, error }
}
Architectural Patterns for Enterprise Applications
For large-scale applications, consider advanced architectural patterns:
// Feature-based directory structure
// src/
// ├── features/
// │ ├── authentication/
// │ │ ├── components/
// │ │ ├── screens/
// │ │ ├── services/
// │ │ ├── store/
// │ │ └── index.ts
// │ ├── profile/
// │ └── transactions/
// ├── core/
// │ ├── api/
// │ ├── navigation/
// │ ├── storage/
// │ └── theme/
// ├── shared/
// │ ├── components/
// │ ├── hooks/
// │ └── utils/
// └── App.tsx
// Feature-based directory structure
// src/
// ├── features/
// │ ├── authentication/
// │ │ ├── components/
// │ │ ├── screens/
// │ │ ├── services/
// │ │ ├── store/
// │ │ └── index.ts
// │ ├── profile/
// │ └── transactions/
// ├── core/
// │ ├── api/
// │ ├── navigation/
// │ ├── storage/
// │ └── theme/
// ├── shared/
// │ ├── components/
// │ ├── hooks/
// │ └── utils/
// └── App.tsx
Conclusion
React Native represents a powerful paradigm for developing sophisticated cross-platform applications. By mastering its architectural patterns, performance optimization techniques, and integration capabilities, developers can create applications that deliver exceptional user experiences while maintaining code quality and maintainability.
This guide has introduced advanced concepts and patterns, but the React Native ecosystem continues to evolve rapidly. Stay engaged with the community to discover new techniques and libraries that push the boundaries of mobile application development.