π‘οΈ 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
- Install: DevTools come with React Native
- Open: Shake device β βDebugβ β Opens in browser
- 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
- Always have Error Boundaries - Your appβs big safety net
- Catch async errors - Network fails happen ALL the time
- Use console wisely - Log what matters, not everything
- Donβt ignore warnings forever - Fix them eventually
- Check performance - 60 FPS = happy users
- 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! πͺβ¨
