Debugging Guide
How to fix things when they break
Debugging React Native
Mobile development has more moving parts than web. Here is how to keep your sanity.
1. The Developer Menu
Shake your device (or press Cmd+D in iOS Simulator, Cmd+M in Android Emulator) to open the Dev Menu.
- Reload: Refreshes the JS bundle.
- Toggle Element Inspector: Lets you tap on UI elements to see their styles and box model.
2. Console Debugging
console.log works, but it prints to your terminal running npx expo start.
To see logs in a structured way:
- Press
jin the terminal to open the Debugger. - Or use React Native Debugger (standalone app).
3. Common "Red Screen" Errors
"Undefined is not an object"
You are trying to access a property of something that doesn't exist.
- Fix: Check your data fetching. Use optional chaining:
user?.name.
"Text strings must be rendered within a Text component"
You have random text inside a View.
- Bad:
<View>Hello</View> - Good:
<View><Text>Hello</Text></View> - Tricky Case:
return <View>{isPresent && <Component />}</View>-> IfisPresentis0, React renders "0", which crashes RN. Use!!isPresentorisPresent ? : null.
"Network Request Failed"
- On Android,
localhostdoes not refer to your computer. It refers to the phone itself. - Fix: Use your computer's local IP (e.g.,
http://192.168.1.5:3000) or use10.0.2.2for Android Emulator.
4. Error Boundaries
Wrap your app in an Error Boundary to catch crashes in production and show a "Something went wrong" screen instead of closing the app.
Jsx
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <Text>Something went wrong.</Text>;
}
return this.props.children;
}
}Summary Checklist
- Know how to open the Dev Menu.
- Use
Optional Chaining (?.)to prevent undefined crashes. - Handle
localhostcorrectly on Android.