What is React Native?

React Native is a framework created by Facebook that lets you build mobile apps for iOS and Android using JavaScript and React. Think of it like writing a letter once and having it automatically translated into different languages - you write your code once, and it runs on both iPhone and Android devices.

Unlike traditional hybrid apps that run inside a web browser, React Native creates real native components. It's like building with LEGO blocks - you use the same building blocks (JavaScript code) to create actual native mobile interfaces that look and feel like apps built with Swift or Kotlin.

Why Choose React Native?

  • Write Once, Run Everywhere: One codebase for iOS and Android saves time and effort
  • Real Native Performance: Uses actual native components, not web views
  • Hot Reloading: See changes instantly without rebuilding the entire app
  • Huge Community: Thousands of libraries and active developer support
  • JavaScript Familiarity: Use your existing JavaScript/React skills
  • Cost Effective: One team can build both iOS and Android apps
  • Fast Development: Build apps 30-40% faster than native development

When to Use React Native?

Perfect For:

  • Apps with standard UI components (social media, e-commerce, news apps)
  • MVP (Minimum Viable Product) to test market quickly
  • Teams with strong JavaScript expertise
  • Apps that need frequent updates and iterations
  • Business apps with forms, lists, and data display
  • Apps with similar functionality on both platforms

Consider Native Instead When:

  • Building performance-critical apps (heavy games, video editing)
  • Need very platform-specific features or advanced animations
  • Working with Bluetooth, advanced camera features extensively
  • App requires low-level hardware integration

Core Components

React Native provides building blocks similar to HTML elements, but these compile to real native UI components:

import React from 'react';
import { View, Text, Image, ScrollView, TextInput } from 'react-native';

// View = Container (like <div> in HTML)
// Text = Text display (like <p> or <span>)
// Image = Display images
// ScrollView = Scrollable container
// TextInput = Input field

function WelcomeScreen() {
  return (
    <View style={{ flex: 1, padding: 20 }}>
      <Text style={{ fontSize: 24, fontWeight: 'bold' }}>
        Welcome to React Native!
      </Text>

      <Image
        source={{ uri: 'https://example.com/logo.png' }}
        style={{ width: 100, height: 100 }}
      />

      <TextInput
        placeholder="Enter your name"
        style={{ borderWidth: 1, padding: 10, marginTop: 20 }}
      />
    </View>
  );
}

Think of components as:

  • View: A box or container (like a drawer to organize things)
  • Text: Any text you want to display (labels, paragraphs)
  • Image: Pictures or icons
  • Button: Clickable buttons for actions
  • FlatList: Efficient scrolling lists (like Instagram feed)

State Management

State is like your app's memory - it remembers information and updates the screen when that information changes. Think of it like a thermostat that remembers the current temperature and updates the display when it changes.

import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

function Counter() {
  // useState creates a piece of memory for our count
  // count = current value, setCount = function to update it
  const [count, setCount] = useState(0);

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 32 }}>Count: {count}</Text>

      <Button
        title="Add One"
        onPress={() => setCount(count + 1)}
      />

      <Button
        title="Reset"
        onPress={() => setCount(0)}
      />
    </View>
  );
}

Managing Form Input:

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    console.log('Email:', email);
    console.log('Password:', password);
    // Send to backend API
  };

  return (
    <View style={{ padding: 20 }}>
      <TextInput
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
      />

      <TextInput
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
        style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
      />

      <Button title="Login" onPress={handleLogin} />
    </View>
  );
}

Navigation Between Screens

Navigation is how users move between different screens in your app - like turning pages in a book. React Navigation is the most popular library for this.

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

const Stack = createNativeStackNavigator();

// Screen 1: Home
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ fontSize: 24 }}>Home Screen</Text>
      <Button
        title="Go to Profile"
        onPress={() => navigation.navigate('Profile', { userId: 123 })}
      />
    </View>
  );
}

// Screen 2: Profile
function ProfileScreen({ route }) {
  const { userId } = route.params;

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Profile Screen for User: {userId}</Text>
    </View>
  );
}

// Main App with Navigation
function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Navigation Types:

  • Stack Navigation: Push screens like a deck of cards (most common)
  • Tab Navigation: Bottom tabs like Instagram (Home, Search, Profile)
  • Drawer Navigation: Side menu that slides in from left/right

Native Modules

Native modules let you access device features that JavaScript alone can't reach - like the camera, GPS, or fingerprint sensor. Think of them as bridges connecting JavaScript to the phone's hardware.

// Using Camera
import { Camera } from 'react-native-vision-camera';

function CameraScreen() {
  const camera = useRef(null);

  const takePhoto = async () => {
    const photo = await camera.current.takePhoto();
    console.log('Photo saved:', photo.path);
  };

  return (
    <View style={{ flex: 1 }}>
      <Camera ref={camera} style={{ flex: 1 }} />
      <Button title="Take Photo" onPress={takePhoto} />
    </View>
  );
}

// Using Geolocation
import Geolocation from '@react-native-community/geolocation';

function LocationScreen() {
  const [location, setLocation] = useState(null);

  const getLocation = () => {
    Geolocation.getCurrentPosition(
      (position) => {
        setLocation({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        });
      },
      (error) => console.log(error),
      { enableHighAccuracy: true }
    );
  };

  return (
    <View>
      <Button title="Get Location" onPress={getLocation} />
      {location && (
        <Text>
          Lat: {location.latitude}, Long: {location.longitude}
        </Text>
      )}
    </View>
  );
}

Common Native Features:

  • Camera & Photos: Take pictures, access photo library
  • Location: GPS coordinates, maps integration
  • Storage: Save data locally on device
  • Push Notifications: Alert users even when app is closed
  • Biometrics: Fingerprint, Face ID authentication
  • Contacts: Access phone's contact list

Styling in React Native

React Native uses a JavaScript object for styling, similar to CSS but with camelCase property names:

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

function StyledComponent() {
  return (
    <View style={styles.container}>
      <Text style={styles.heading}>Hello World</Text>
      <Text style={styles.subtext}>Welcome to React Native</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
    justifyContent: 'center',  // CSS: justify-content
    alignItems: 'center'        // CSS: align-items
  },
  heading: {
    fontSize: 28,               // No units needed (automatically dp/pt)
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 10
  },
  subtext: {
    fontSize: 16,
    color: '#666'
  }
});

Fetching Data from APIs

Most apps need to get data from the internet. Here's how to fetch data from a backend API:

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  // Fetch data when component loads
  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await fetch('https://api.example.com/users');
      const data = await response.json();
      setUsers(data);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching users:', error);
      setLoading(false);
    }
  };

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  return (
    <FlatList
      data={users}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => (
        <View style={{ padding: 15, borderBottomWidth: 1 }}>
          <Text style={{ fontSize: 18 }}>{item.name}</Text>
          <Text style={{ color: '#666' }}>{item.email}</Text>
        </View>
      )}
    />
  );
}

Best Practices

  • Use Functional Components: Prefer hooks (useState, useEffect) over class components
  • Optimize Lists: Use FlatList instead of ScrollView for long lists
  • Avoid Inline Styles: Use StyleSheet.create for better performance
  • Handle Loading States: Always show loading indicators during API calls
  • Error Handling: Use try-catch blocks for async operations
  • Platform-Specific Code: Use Platform.OS when needed for iOS/Android differences
  • Test on Real Devices: Simulators don't show real performance
  • Keep Components Small: Break large components into smaller, reusable pieces
  • Use TypeScript: Adds type safety and better IDE support
  • Manage State Wisely: Use Context API or Redux for global state

React Native vs Other Frameworks

React Native vs Flutter:

  • React Native uses JavaScript (more developers know it)
  • Flutter uses Dart (newer language, smaller community)
  • React Native has more third-party libraries
  • Flutter has slightly better performance and smoother animations
  • React Native is better if you already know React

React Native vs Native Development:

  • React Native: One codebase, faster development, good performance
  • Native: Two codebases (Swift + Kotlin), best performance, full platform access
  • Choose React Native for 80% of apps, Native for performance-critical apps

Getting Started

Create your first React Native app in minutes:

# Install Expo CLI (easiest way to start)
npm install -g expo-cli

# Create new project
npx create-expo-app MyFirstApp

# Navigate to project
cd MyFirstApp

# Start development server
npx expo start

# Scan QR code with Expo Go app on your phone
# Your app will appear on your device!

Ready to Build Mobile Apps?

Master React Native and create professional iOS and Android applications

Explore Hybrid Mobile App Course

Related Topics