DEV Community

Odipo Otieno (KwargDevs)
Odipo Otieno (KwargDevs)

Posted on

Beginner Friendly React Native Notes

Of course! Here are comprehensive learning notes for React Native, designed for someone with your background (some JS, some React).

These notes follow your table of contents, focusing on core concepts, practical examples, and drawing parallels to what you might already know from web React.


React Native Learning Notes

Key Mindset: You already know the logic of React (components, props, state). Your main task is learning the new building blocks for mobile. Instead of <div> and <p>, you'll use <View> and <Text>.


πŸ“˜ Beginner Stage – Foundations

Introduction to React Native

  • What is React Native?

    • It's a JavaScript framework for building truly native mobile apps for both iOS and Android from a single codebase.
    • It was created by Facebook (now Meta).
    • Your JavaScript code is not running in a web-view. It runs on a separate JavaScript thread and communicates with the native platform (iOS/Android).
    • Motto: "Learn once, write anywhere."
  • React Native vs Native Development

    • Native:
      • Android: Java or Kotlin with Android Studio.
      • iOS: Swift or Objective-C with Xcode.
      • Pros: Best possible performance, full access to all device features immediately.
      • Cons: Two separate codebases, two teams (or one person learning two very different ecosystems), slower development time.
    • React Native:
      • Pros: One codebase for both platforms, faster development, larger developer pool (JS developers), hot-reloading for instant feedback.
      • Cons: Performance can be slightly less than pure native in very intensive apps (e.g., 3D games), might need to wait for community libraries for brand new native features.
  • How React Native Works (The Bridge)

    • Imagine your app has two sides: the JavaScript side (where your React code lives) and the Native side (the actual iOS/Android UI).
    • These two sides can't talk to each other directly. They communicate over the JavaScript Bridge.
    • When you write <Button title="Press Me" />, your JS code sends a serialized JSON message across the bridge saying, "Hey Native side, please render a native button with the text 'Press Me'."
    • The Native side receives this, renders a real UIButton (iOS) or Button widget (Android), and sends events (like a press) back across the bridge to your JS code.
    • This is why it feels "native" – because it is using native UI components.
  • Popular apps built with React Native:

    • Facebook/Instagram (parts of it)
    • Discord
    • Pinterest
    • Shopify
    • Coinbase
    • Tesla

Setting Up the Environment

You have two main paths. Start with Expo. It's much, much easier for beginners.

  • 1. Install Core Dependencies:

    • Node.js: JavaScript's runtime. You need this to run Metro (React Native's bundler) and the CLI tools. Get the LTS version.
    • Watchman: A file-watching service by Facebook. Recommended for performance, especially on macOS.
    • JDK (Java Development Kit): Required if you want to build for Android. Use a recommended version like JDK 11 (often distributed as Zulu OpenJDK).
  • 2. Install Native Tools (Only needed for React Native CLI, not Expo Go):

    • Android Studio: The official IDE for Android. You need it to install the Android SDK and to run virtual devices (emulators).
    • Xcode (macOS only): The official IDE for iOS. You need it to install the iOS SDK and run simulators. You can only build/run iOS apps on a Mac.
  • 3. Install a CLI:

    • Expo CLI (Recommended for Beginners):
      • What it is: A set of tools and services built around React Native that makes development, building, and publishing much simpler.
      • Pros:
        • Fastest setup. No need to install Android Studio/Xcode to get started.
        • Develop on your physical phone with the "Expo Go" app.
        • Simple, managed builds and updates (EAS - Expo Application Services).
        • Lots of common native APIs (Camera, Location, etc.) are pre-packaged.
      • Cons: Less flexibility if you need to write your own custom native code. (This is rare for beginners).
    • React Native CLI (The "Bare" Workflow):
      • What it is: The default React Native experience. You have full control.
      • Pros: Full control, can link any native library, can write your own native modules.
      • Cons: Much more complex setup (Android Studio/Xcode configuration is required), slower to get started.
  • Creating Your First App (with Expo):

    # Install the Expo CLI globally
    npm install -g expo-cli
    
    # Create a new project
    expo init MyFirstApp
    
    # Navigate into the project directory
    cd MyFirstApp
    
    # Start the development server
    npm start
    

    This will open a terminal with a QR code. Download the "Expo Go" app on your phone and scan the code. Your app will appear on your device!

JavaScript Essentials (Quick Refresher)

  • Variables, etc.: You already know let, const, function, arrays, and objects. They work exactly the same.
  • ES6+ Features (You will use these constantly):
    • Arrow Functions: const MyComponent = () => <View />;
    • Destructuring: const { name, age } = userObject; and const MyComponent = ({ title }) => <Text>{title}</Text>; (for props).
    • Spread/Rest: const newStyles = { ...oldStyles, color: 'red' };
  • Async/Await & Promises: Crucial for fetching data from an API.

    // This is a very common pattern
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const json = await response.json();
        console.log(json);
      } catch (error) {
        console.error("Oops, something went wrong:", error);
      }
    };
    

React Basics (The React Native Way)

  • Components: The fundamental building blocks. Same concept as React, but you import from react-native.

    import React from 'react';
    import { View, Text, Button } from 'react-native'; // <-- Import mobile components
    
    const Greeting = ({ name }) => {
      return (
        <View>
          <Text>Hello, {name}!</Text>
        </View>
      );
    };
    
    export default Greeting;
    
  • JSX Syntax: Exactly the same, but with different tags.

    • <div> becomes <View> (a generic container).
    • <p>, <h1>, <span> become <Text> (all text must be inside a <Text> tag).
    • <img /> becomes <Image />.
    • <button> becomes <Button />.
  • Props & State: Identical to React.

    • Props: Pass data down from parent to child. <Greeting name="Alice" />
    • State: Manage a component's internal data. The useState hook is your best friend.
    import React, { useState } from 'react';
    import { View, Text, Button } from 'react-native';
    
    const Counter = () => {
      const [count, setCount] = useState(0); // <-- useState is the same!
    
      return (
        <View>
          <Text>You clicked {count} times</Text>
          <Button
            title="Click Me"
            onPress={() => setCount(count + 1)} // <-- Event handling
          />
        </View>
      );
    };
    
  • Event Handling:

    • onClick becomes onPress. This is the most common one.
    • Used on Button, TouchableOpacity, Pressable, etc.
  • Conditional Rendering: Exactly the same. Use &&, ternary operators, or if statements.

    {isLoggedIn && <Text>Welcome Back!</Text>}
    
  • List Rendering: Use the .map() method, just like in React. Always provide a key.

    const users = [{id: '1', name: 'Alice'}, {id: '2', name: 'Bob'}];
    
    <View>
      {users.map(user => (
        <Text key={user.id}>{user.name}</Text>
      ))}
    </View>
    

    Note: For long lists, you'll later learn about <FlatList> for better performance.


βš™οΈ Intermediate Stage – Core React Native Concepts

Styling in React Native

  • No CSS files! All styling is done in JavaScript.
  • Styles are written as JS objects. Property names are camelCased (e.g., backgroundColor instead of background-color).
  • Flexbox in RN:
    • This is the primary layout system. It works very similarly to web Flexbox.
    • Key difference: The default flexDirection is 'column' (top-to-bottom), not 'row'.
  • StyleSheet API:

    • The best practice is to use StyleSheet.create({}).
    • It creates optimized, immutable style objects and moves them off the main JS thread, which is good for performance.
    import { StyleSheet, View, Text } from 'react-native';
    
    const MyCard = () => (
      <View style={styles.container}>
        <Text style={styles.title}>Hello World</Text>
      </View>
    );
    
    // Define styles at the bottom of the file
    const styles = StyleSheet.create({
      container: {
        flex: 1, // Take up all available space
        justifyContent: 'center', // Center children vertically
        alignItems: 'center',    // Center children horizontally
        backgroundColor: '#f5f5f5',
      },
      title: {
        fontSize: 24,
        fontWeight: 'bold', // fontWeight is a string, not a number
        color: '#333',
      },
    });
    
  • Platform-specific styling:

    • Use the Platform module.
    import { Platform, StyleSheet } from 'react-native';
    
    const styles = StyleSheet.create({
      header: {
        paddingTop: Platform.OS === 'ios' ? 20 : 0, // Add padding only for iOS status bar
      },
    });
    

Navigation

  • Apps have multiple screens. You need a way to navigate between them.
  • React Navigation: The community-standard library for this.
  • Stack Navigator:
    • Like a stack of cards. You push new screens on top and pop them off to go back.
    • Use for flows like: List -> Detail Page -> Edit Page.
  • Tab Navigator:
    • A bar of tabs at the bottom (or top) of the screen.
    • Use for main sections of your app: Home, Profile, Settings.
  • Drawer Navigator:
    • A menu that slides out from the side.
    • Use for less-frequently accessed screens or as a primary navigation on larger devices.

Working with User Input

  • <TextInput>: The equivalent of <input type="text">.
    • Props: onChangeText, value, placeholder, secureTextEntry (for passwords), keyboardType.
  • <Button>: A simple, basic button with limited styling.
  • <TouchableOpacity> / <Pressable>: Wrappers to make any <View> or <Text> pressable. TouchableOpacity lowers opacity on press. Pressable is more modern and flexible. Use these for custom buttons.
import React, { useState } from 'react';
import { View, TextInput, Button, Text, TouchableOpacity, StyleSheet } from 'react-native';

const LoginForm = () => {
  const [email, setEmail] = useState('');

  return (
    <View>
      <TextInput
        style={styles.input}
        placeholder="Enter your email"
        value={email}
        onChangeText={setEmail} // Simplified syntax for (text) => setEmail(text)
        keyboardType="email-address"
        autoCapitalize="none"
      />
      <TouchableOpacity style={styles.customButton} onPress={() => alert('Logged in!')}>
        <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

State Management

  • useState & useEffect Hooks: Your bread and butter for local component state and side effects (like API calls).
  • useContext for Global State:
    • Problem: "Prop drilling" - passing props down through many layers of components that don't need them.
    • Solution: useContext lets you create a "global" state that any component inside its Provider can access directly, without props. Good for things like theme (dark/light mode) or user authentication status.
  • Intro to Redux & Redux Toolkit:
    • When to use it: For very large, complex apps where many components need to share and update the same state in a predictable way.
    • Redux Toolkit (RTK): The modern, recommended way to use Redux. It simplifies a lot of the old "boilerplate" code.
  • Zustand or Jotai (Modern Alternatives):
    • Much simpler to set up and use than Redux.
    • Zustand: Feels like a simple useState hook for global state. Very popular and a great first step beyond useContext.

APIs and Data Fetching

  • Fetch & Axios:
    • fetch is built-in to React Native. Works just like in the browser.
    • axios is a popular third-party library that adds features like automatic JSON parsing, timeout handling, and easier error management.
  • useEffect for API Calls: The standard pattern is to fetch data inside a useEffect with an empty dependency array [] so it only runs once when the component mounts.
import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';

const PostList = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Define the async function inside useEffect
    const fetchPosts = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        console.error(error);
      } finally {
        setLoading(false); // Stop loading indicator
      }
    };

    fetchPosts(); // Call it
  }, []); // [] means this effect runs only once

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

  return (
    <View>
      {posts.map(post => <Text key={post.id}>{post.title}</Text>)}
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

Async Storage and Local Data

  • Sometimes you need to save data on the user's device.
  • AsyncStorage:

    • A simple, unencrypted, key-value storage system.
    • Think of it like localStorage on the web.
    • Good for storing user settings, a JWT token, etc.
    • Important: It's asynchronous! Every operation returns a Promise. * ```javascript import AsyncStorage from '@react-native-async-storage/async-storage';

    const storeData = async (key, value) => {
    await AsyncStorage.setItem(key, value);
    };
    const getData = async (key) => {
    return await AsyncStorage.getItem(key);
    };

    
    
  • Secure Storage: For sensitive data like tokens or user credentials, use a library like react-native-keychain which uses the phone's secure hardware (Keychain on iOS, Keystore on Android).

  • SQLite / Realm: For large amounts of structured data (e.g., a list of 10,000 products, chat messages), you need a real database. These are the most common choices.


πŸš€ Advanced Stage – Professional Skills

This is where you go from building apps to building good apps.

  • Performance Optimization:

    • FlatList: When rendering long lists, do not use .map(). Use <FlatList>. It virtualizes the list, meaning it only renders the items currently visible on screen, saving a huge amount of memory and processing.
    • Memoization:
      • React.memo: A wrapper for your component. It prevents it from re-rendering if its props haven't changed. export default React.memo(MyComponent);
      • useMemo: Memoizes a value (e.g., the result of an expensive calculation).
      • useCallback: Memoizes a function. Useful when passing functions as props to memoized child components.
  • Native Modules & Platform APIs:

    • The "escape hatch" for when React Native doesn't have a feature built-in.
    • You can access native device APIs like the Camera, GPS (Location), Vibration, and Permissions using libraries provided by Expo or the community.
    • Permissions: You must always ask the user for permission before accessing sensitive info like their location or camera. Use a library like expo-permissions or react-native-permissions.
  • Animations:

    • Animated API: The basic, built-in API. It's powerful but can be verbose.
    • Reanimated 2: The modern, de-facto standard. It allows you to run complex animations entirely on the native UI thread, making them incredibly smooth and performant. It's a must-learn for advanced animations.
    • Gesture Handler: Works hand-in-hand with Reanimated to create smooth, interruptible gesture-based animations (like dragging, swiping, pinching).
  • Testing:

    • Unit Testing (Jest): Test individual functions or components in isolation.
    • Integration Testing (React Native Testing Library): Test how components work together. You render a component and check that it behaves correctly from a user's perspective.
    • End-to-End (E2E) Testing (Detox): An automated script that installs your app on a simulator and "taps" through it like a real user to test entire user flows.
  • Debugging and Logging:

    • Flipper: The recommended debugging tool. It's a desktop app that lets you inspect your app's network requests, logs, component hierarchy, and much more.
    • Remote Debugging: Lets you use Chrome's DevTools to debug your JS code, set breakpoints, etc.
  • TypeScript in React Native:

    • Why?: To add static types to your JavaScript code. This catches a huge number of bugs before you run your app (e.g., passing a number where a string is expected).
    • Typing Props & State:

      // Define the shape of your props
      type GreetingProps = {
        name: string;
      };
      
      const Greeting: React.FC<GreetingProps> = ({ name }) => {
        return <Text>Hello, {name}!</Text>;
      };
      
      const [count, setCount] = useState<number>(0); // Type your state
      
    • Highly recommended for any serious project.


πŸ“² Deployment & Production

  • Building and Publishing:
    • Expo (EAS Build): The easiest way. You run one command (eas build), and Expo builds your app in the cloud for both Android and iOS and provides the final files (.aab for Android, .ipa for iOS).
    • Bare Workflow (Manual): You use Android Studio to generate a signed APK/AAB and Xcode to archive and upload your app to the App Store Connect. This is more complex.
  • App Store Optimization:
    • Make sure you have high-quality App Icons, a Splash Screen (the first thing a user sees), and compelling Screenshots and descriptions.
  • Firebase Crashlytics & Analytics:
    • Crashlytics: Automatically reports crashes in your production app, so you know what's breaking for your users. Essential.
    • Analytics: See how users are interacting with your app (which screens they visit, which buttons they press).

🌐 Real World Projects and Freelancing

  • Cloning Real Apps: The best way to learn is by building. Pick an app you use and try to rebuild its UI and core features.
  • Using 3rd Party Libraries: You don't build everything from scratch.
    • UI Libraries: React Native Paper (Material Design), NativeBase, Tamagui give you pre-styled, beautiful components to build your app faster.
    • Services: Firebase (backend-in-a-box), Stripe (payments), OneSignal (push notifications), Lottie (for complex animations).
  • Freelancing and Job Readiness:
    • Portfolio: Your GitHub profile is your resume. Have 2-3 polished apps that you can show potential employers.
    • Git: You must be proficient with Git (commit, push, pull, branch, merge).
    • Resume Prep: Highlight the projects you've built, the technologies you've used (React Navigation, Redux/Zustand, TypeScript, etc.), and any problems you've solved (e.g., "optimized list performance using FlatList").

Final Advice: Start small. Start with Expo. Build things. The theory is important, but you will learn 10x faster by actually writing code, hitting errors, and figuring out how to solve them. Good luck

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.