Error Handling and Debug

Back

Loading concept...

πŸ›‘οΈ Error Handling & Debug in React Native

The Safety Net Story

Imagine you’re a trapeze artist in a circus. You do amazing flips high in the air! But what happens if you slip? You need a safety net below to catch you.

That’s exactly what error handling does in your React Native app. Your app is the trapeze artist doing amazing tricks (features). Sometimes things go wrong (bugs!). Error handling is your safety netβ€”it catches problems before your whole app crashes.


πŸŽͺ Meet Your Safety Crew

Think of debugging and error handling like having a circus safety crew:

Safety Crew Member What They Do
Error Boundaries The big safety net under the trapeze
Component Error Handling Mini nets for each performer
Async Error Handling Catches slips during flying tricks
Console Debugging The announcer telling you what’s happening
LogBox API The warning signs around the ring
React DevTools X-ray glasses to see inside performers
Performance Monitor The stopwatch timing every move
Hermes Engine The super-powered engine making everyone faster

1️⃣ Error Boundaries - The Big Safety Net

What Is It?

An Error Boundary is like a big safety net. If any part of your app falls (crashes), the net catches it so the WHOLE circus doesn’t stop.

Simple Example

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.log('Caught error:', error);
  }

  render() {
    if (this.state.hasError) {
      return <Text>Oops! Something broke.</Text>;
    }
    return this.props.children;
  }
}

How To Use It

<ErrorBoundary>
  <MyApp />
</ErrorBoundary>

Think of it like this: Wrap your whole app in a safety net. If something inside breaks, users see β€œOops!” instead of a scary crash.


2️⃣ Component Error Handling - Mini Safety Nets

What Is It?

Each performer (component) can have their own small net. If just ONE performer slips, only their act stopsβ€”not the whole show!

Simple Example

const UserProfile = () => {
  const [error, setError] = useState(null);

  if (error) {
    return <Text>Could not load profile</Text>;
  }

  return (
    <View>
      <Text>Welcome, User!</Text>
    </View>
  );
};

Try-Catch In Components

const loadData = () => {
  try {
    // Do something risky
    const result = JSON.parse(data);
    setUser(result);
  } catch (err) {
    setError('Data is broken!');
  }
};

Real Life: If loading your profile picture fails, you still see your name. Only the broken part shows an error.


3️⃣ Async Error Handling - Catching Flying Tricks

What Is It?

When trapeze artists are mid-air (async operations like fetching data from internet), you need special timing to catch them.

The Problem

// 🚫 BAD - Error flies away uncaught!
const fetchData = async () => {
  const response = await fetch(url);
  const data = await response.json();
};

The Solution

// βœ… GOOD - Error is caught!
const fetchData = async () => {
  try {
    const response = await fetch(url);
    const data = await response.json();
    setData(data);
  } catch (error) {
    setError('Network problem!');
  }
};

Promise Catch Method

fetch(url)
  .then(res => res.json())
  .then(data => setData(data))
  .catch(err => setError('Failed!'));

Think of it: The internet is unreliable. ALWAYS have a catch ready for when things go wrong.


4️⃣ Console Debugging - The Announcer

What Is It?

The announcer tells the audience what’s happening. Console tells YOU what’s happening inside your app.

Your Debugging Toolkit

// Simple message
console.log('App started!');

// With a label
console.log('User data:', userData);

// Warning - yellow flag
console.warn('This is slow!');

// Error - red alert
console.error('Something broke!');

// Group related logs
console.group('User Login');
console.log('Step 1: Check password');
console.log('Step 2: Verify email');
console.groupEnd();

Pro Tip: Conditional Logging

const DEBUG = true;

const log = (msg) => {
  if (DEBUG) console.log(msg);
};

log('Only shows in dev mode!');

5️⃣ LogBox API - Warning Signs

What Is It?

LogBox shows warning signs in your app. Yellow for warnings, red for errors. Like traffic signs telling you β€œSlow down!” or β€œStop!”

Control Your Warnings

import { LogBox } from 'react-native';

// Ignore one specific warning
LogBox.ignoreLogs([
  'Warning: Each child'
]);

// Ignore ALL logs (not recommended!)
LogBox.ignoreAllLogs();

// Install custom handler
LogBox.install();

When To Use

// Hiding noisy library warnings
LogBox.ignoreLogs([
  'Require cycle:'
]);

// But NEVER hide YOUR errors!

Warning: Don’t ignore warnings forever. Fix them when you can!


6️⃣ React DevTools - X-Ray Glasses

What Is It?

X-ray glasses let you see INSIDE your app. See every component, every piece of state, every prop. Magic!

How To Use

  1. Install: DevTools come with React Native
  2. Open: Shake device β†’ β€œDebug” β†’ Opens in browser
  3. Inspect: Click any component to see its insides

What You Can See

πŸ“± App
  └── πŸ“¦ UserProfile
      β”œβ”€β”€ props: { name: "Alex" }
      β”œβ”€β”€ state: { loading: false }
      └── πŸ“¦ Avatar
          └── props: { url: "..." }

Standalone DevTools

# Install globally
npm install -g react-devtools

# Run it
react-devtools

Real Life: When something looks wrong, use DevTools to see what data each component actually has.


7️⃣ Performance Monitor - The Stopwatch

What Is It?

A stopwatch that times everything. Is your app running at 60 FPS (smooth like butter) or 15 FPS (choppy like a slideshow)?

Enable It

// Shake device β†’ "Perf Monitor"
// Or in code:
import { PerfMonitor } from 'react-native';
PerfMonitor.toggle();

What You See

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ JS: 60 FPS  UI: 60 FPS  β”‚
β”‚ RAM: 45 MB              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Reading The Numbers

Metric Good Bad
JS FPS 60 Below 30
UI FPS 60 Below 30
RAM Stable Growing constantly

Find Slow Parts

import { Profiler } from 'react';

<Profiler id="MyList" onRender={(id, phase, duration) => {
  console.log(`${id} took ${duration}ms`);
}}>
  <MyList />
</Profiler>

8️⃣ Hermes Engine - Super Speed

What Is It?

Hermes is like giving your circus performers jet packs! It’s a special JavaScript engine made by Facebook that makes React Native apps start faster and use less memory.

Is Hermes Enabled?

const isHermes = () => {
  return !!global.HermesInternal;
};

console.log('Hermes?', isHermes());

Enable Hermes (android/app/build.gradle)

project.ext.react = [
    enableHermes: true
]

Enable Hermes (iOS Podfile)

use_react_native!(
  :hermes_enabled => true
)

Hermes Benefits

Without Hermes With Hermes
4 second startup 1.5 second startup
200 MB memory 80 MB memory
Slower JS Faster JS

Debugging With Hermes

// Same console methods work!
console.log('Hermes is fast!');

// Check version
if (global.HermesInternal) {
  console.log(
    HermesInternal.getRuntimeProperties()
  );
}

🎯 Quick Decision Guide

graph TD A["Error Happened!"] --> B{Where?} B --> C["In Component?"] B --> D["In Async Code?"] B --> E[Don't know?] C --> F["Use try-catch"] D --> G["Use .catch or try-catch"] E --> H["Wrap in Error Boundary"] F --> I["Show friendly error"] G --> I H --> I

πŸ† Golden Rules

  1. Always have Error Boundaries - Your app’s big safety net
  2. Catch async errors - Network fails happen ALL the time
  3. Use console wisely - Log what matters, not everything
  4. Don’t ignore warnings forever - Fix them eventually
  5. Check performance - 60 FPS = happy users
  6. Enable Hermes - Free speed boost!

πŸŽͺ Your Safety Checklist

  • [ ] Wrapped app in Error Boundary
  • [ ] All fetch calls have catch
  • [ ] Console logs for debugging
  • [ ] LogBox configured
  • [ ] Know how to use DevTools
  • [ ] Performance Monitor checked
  • [ ] Hermes enabled

Remember: Every great trapeze artist has a safety net. Every great app has error handling. You’re now ready to perform amazing tricks safely! πŸŽͺ✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.