0% found this document useful (0 votes)
4 views19 pages

Debugging React Native

This course section focuses on debugging in React Native, teaching participants how to understand and fix errors using tools like React Native DevTools and Expo. It emphasizes the importance of reading error messages, utilizing debugging techniques, and developing a systematic approach to problem-solving. By the end of the section, learners will be equipped to analyze errors, debug UI issues, and confidently resolve bugs independently.

Uploaded by

Rakesh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Debugging React Native

This course section focuses on debugging in React Native, teaching participants how to understand and fix errors using tools like React Native DevTools and Expo. It emphasizes the importance of reading error messages, utilizing debugging techniques, and developing a systematic approach to problem-solving. By the end of the section, learners will be equipped to analyze errors, debug UI issues, and confidently resolve bugs independently.

Uploaded by

Rakesh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

📘 Course Section Overview: Debugging in React Native

🎯 Objective:

 Learn how to understand and fix errors


 Use React Native DevTools and Expo tools for effective debugging
 Develop the ability to analyze and trace problems while building your UI

🧠 Why Debugging is Critical in React Native


Even if you’re great at coding:

 ❌ Errors will happen


 🧩 Unexpected behavior may occur
 🐛 Bugs will sneak into your UI or logic

A professional developer must be able to:

1. Read and interpret error messages


2. Use debugging tools efficiently
3. Inspect the UI during development
4. Understand runtime warnings and logs
5. Isolate, reproduce, and solve issues

🔎 1. Understanding Error Messages in React Native

❗ What happens when something breaks?

React Native apps throw red screen errors with stack traces that contain:

 File and line number


 Component or function name
 Helpful hint messages (sometimes)
📌 Developer Goals:

 Read where the error occurred (filename.js:line)


 Understand why it happened (type mismatch, null access, missing import, etc.)
 Follow the stack trace hierarchy

✅ Tip:

Use the error screen as a guide — don’t panic. Start from the top-most file/line and work down the
trace.

🔧 2. Hands-on Debugging Tools & Techniques


React Native + Expo gives you built-in dev tools:

🔍 Debugging Techniques You Will Learn:


Tool Description
Console logs (console.log) Basic but powerful for tracking values, states
Error boundaries (in code) Try-catch blocks or component-level error handling
React Native Error Screen Red error screen that shows where and what went wrong
React DevTools Visualize component tree, props, and state
Expo DevTools in browser Control build, open logs, reload, and run simulator
Connect JavaScript execution to browser for step-by-step
Remote Debugging with Chrome
analysis
npx expo start --dev-client Advanced debugging in development mode

🧰 Debugging Setup with Expo

✅ When using Expo:

 Start project:
 npx expo start

 This opens Expo Developer Tools in your browser:


o View logs
o Send app to simulator/device
o Enable hot reloading or fast refresh
o Access console logs in real-time
🪲 Example Debugging Process (Summary from Upcoming Lectures)
In the rest of this debugging section, you’ll learn by:

 Introducing intentional bugs


 Watching the app crash or misbehave
 Reading the error output
 Tracing the source of error
 Fixing issues while explaining the logic

You’ll also learn:

 What common errors mean (e.g., undefined is not an object)


 Why type mismatches occur
 How invalid JSX or props cause runtime crashes

🔁 If You Skipped Previous Sections


🔁 This course continues from a previous app project.

If you missed it:

 You’ll get the project files attached with this section


 Download and follow along, so you’re not left behind
 It’s crucial to have a working example app to debug effectively

🧑‍💻 Pro Debugging Mindset

When an error occurs:

Don't say "It’s broken" – say "Let me trace what happened."

Ask yourself:

1. What broke?
2. Where did it happen? (file/line/component)
3. Why did it break? (missing state, null value, etc.)
4. How can I confirm it? (console.log, component trace)
5. What’s the fix or workaround?

🧠 Summary: What You’ll Be Able to Do After This Section


✅ Read and analyze red screen errors
✅ Debug UI issues using React Native DevTools
✅ Use Expo’s browser-based debugging system
✅ Use logging and error boundaries effectively
✅ Build confidence in resolving bugs independently

🧠 React Native Debugging: Understanding Error Messages

🎯 Goal:

To explore how React Native error messages work, how to interpret them, and how to debug your app
when things break.

💥 Intentionally Causing an Error: Practical Example


In the GoalInput.js file, the instructor intentionally causes an error:

<Image source="some/path/to/image.png" />

This line is wrong for two reasons:

1. The path is invalid — the image doesn’t exist.


2. The format of the source prop is incorrect — it’s a string, whereas the Image component
expects a number when using require().
🛑 Resulting Error & What It Means

Error Message:
Invalid prop 'source' supplied to 'Image'. Expected a number.

🔍 How to Interpret:

 "Invalid prop 'source'": Tells you which prop is wrong (source).


 "Expected a number": Indicates that the Image component expected something like
require(...), which returns a number internally.

🔥 Important Insight: This is not intuitive unless you already know that
require('./path/to/image.png') returns a reference that React Native uses internally (as a
numeric ID) for bundled assets.

📈 Reading the Stack Trace


Error messages also include a stack trace, which is a list of the function/component calls that led to
the error.

How to Read It:

 Ignore top lines – Often point to compiled code (not helpful).


 Look further down – You'll see:
 in GoalInput (created by App)

o Tells you:
 The error happened in GoalInput.js
 It was used by the App component

🧠 Why It Matters:

 If you’re using GoalInput in multiple places, this helps you find which instance is causing the
error.
 This narrows your search area for the bug.
📚 How to Fix It: Correct Way to Load an Image
Instead of using a plain string, use:

<Image source={require('../assets/images/goal.png')} />

✔ Why this works:

 require() tells React Native to bundle and resolve the image during build time.
 This ensures the app knows exactly where and how to find and load the image.

📘 Use the Docs: Your Best Debugging Friend


When you're unsure how to use a component or a prop, consult the official React Native docs.

To check how Image works:

 Go to: https://reactnative.dev/docs/image
 Or search “React Native Image” on Google

Documentation will tell you:

 Acceptable source formats


 How to load images from local assets vs URLs
 Available styling props and behavior

⚠️Warnings vs Errors
Not all issues crash the app. Some are warnings:

 Shown in the emulator log area


 App continues to run, but something doesn’t work as expected
 In this case, the image just doesn't render

🔎 Always click and read warnings — they often prevent future errors.
🖥️Where Errors Show Up
React Native displays errors in multiple places:

Location Description
📱 Emulator red screen Visible immediately if a fatal error occurs
🖥️Terminal (Expo CLI) Logs detailed errors, stack traces, and warnings
🧭 Expo DevTools in browser Also shows some runtime issues
🐛 In-app yellow/red boxes Warnings and exceptions shown directly in-app

✅ Use all these together to get a complete picture of what’s wrong.

✅ Summary: Debugging Lessons from This Example


Step Explanation
🔧 Break the code We used an invalid source prop on an <Image>
🛑 Read the error “Invalid prop source, expected a number”
🔍 Check the trace Found the error in GoalInput used by App
📘 Look at docs Verified correct prop structure for <Image>
✔ Fix it Used require('../assets/images/goal.png')
🔁 Save and test Error disappears; image renders correctly

🧑‍💻 Expert Debugging Mindset


 Errors are clues, not obstacles
 Don’t ignore warnings
 Stack traces guide you to the broken logic
 Use console.log() for step-by-step value tracing
 Learn how each component behaves from the official docs
 Build the habit of asking:

"Where is the error? → Why is it happening? → What does the framework expect? → How
can I fix it?"
🔍 Debugging Without Errors: Understanding the App Flow

💡 Real-World Scenario:

Sometimes, your React Native app runs without any visible errors, but:

 It behaves unexpectedly
 Something doesn’t update
 A state value isn’t what you expect

In these cases, using console.log() is a powerful and straightforward way to inspect the internal
behavior of your app.

🧰 What is console.log()?
 A built-in JavaScript function that prints messages to the console (terminal).
 Helps in:
o Debugging state values
o Tracking code execution
o Understanding component rendering
o Verifying function outputs

🖥️Where Console Logs Show Up


When you use console.log() in your React Native code:

console.log("GoalInput component rendered");

📍 Output Location:

➡️You’ll see the log in the terminal (where npm start or npx expo start was run).

If you’re using multiple emulators or devices:

 You may see the log multiple times (once per instance).
 This helps verify that each instance is running as expected.
📊 Use Cases for Logging

✅ 1. Track Component Lifecycle

You can place a log at the start of a functional component:

function GoalInput(props) {
console.log("GoalInput component rendered");
...
}

Helps you understand:

 How often the component re-renders


 Whether the component is mounted or updated

🧠 Expert Tip: Combine with useEffect() for even better lifecycle tracking.

✅ 2. Monitor State Updates

When using useState() to store data, log the state value:

const [enteredGoalText, setEnteredGoalText] = useState('');

function goalInputHandler(inputText) {
setEnteredGoalText(inputText);
console.log("Updated goal text:", inputText);
}

This helps you verify:

 Whether your event handler is working


 What value is currently stored in the state
 If user input is being received and updated correctly

✅ 3. Debug Event Handlers & Business Logic

Add logs inside:

 Button press handlers


 if/else conditions
 Any custom logic
Example:

function addGoalHandler() {
if (enteredGoalText.trim().length === 0) {
console.log("Empty input. Goal not added.");
return;
}

console.log("Adding goal:", enteredGoalText);


props.onAddGoal(enteredGoalText);
}

🚦 Why Logging is Important


Reason Explanation
🧠 Mental Model Helps you “see” what React Native is doing internally
Timing Shows when a function or component runs
🔄 Re-renders Logs let you know if a component re-rendered unexpectedly
🧪 Testing logic Verifies conditional statements and function outputs
Excessive or repeated logs might indicate a problem (like unnecessary re-
📉 Performance issues
renders)

🧠 Pro Tips for Effective Logging


Tip Explanation
🧩 Label your logs clearly Use meaningful prefixes, like "[AddGoalHandler]"
🎯 Log specific values Instead of "state updated", log "state updated:", value
🔁 Don't overuse Too many logs can clutter your terminal and hide useful info
🧼 Remove or comment out in
Use logging only for dev/debugging — not in final app builds
production
Combine logging with other tools like React DevTools for
💻 Use dev tools if needed
deeper insights

✅ Summary: Becoming a Debugging Pro


Task What to Log Where to Look
See when a component renders Add log at top of component Terminal
Track user input Log inside onChangeText handler Terminal
Debug logic flow Log inside conditionals/functions Terminal
Follow state updates Log inside state update functions Terminal
Check execution order Add logs in multiple parts Terminal in sequence
🚀 Want to Go Further?
You can combine console.log() with:

 useEffect() to log side effects


 React DevTools for inspecting component trees and props
 Custom debug flags (e.g., if (DEBUG) console.log(...))
 Error boundaries to catch render-time crashes

🔧 Advanced Debugging Tools in React Native with Expo

🧭 Why Go Beyond console.log()?

While console.log() is great for basic checks, complex apps require deeper visibility:

 Inspect network requests


 Trace performance issues
 Analyze app structure and state
 Access interactive debug tools

📟 Using Terminal Shortcuts in Expo CLI


When you run your React Native app using:

npm start

or

npx expo start

You launch the Metro Bundler, which gives you access to useful shortcuts.

🔑 To View Shortcuts:

1. Click into the terminal window running Metro (make sure it’s active).
2. Press the ? (question mark) key.
3. You'll see a list of available hotkeys/shortcuts.

🚀 Common Shortcuts:
Shortcut Key Function
A Open Android Emulator
I Open iOS Simulator
R Reload the App
M Open Developer Menu (on Emulator)

💡 These shortcuts only work when the terminal window is selected.

📱 Developer Menu in Emulator


You can open the Developer Menu in different ways:

Platform How to Open


Android Press M in terminal OR Ctrl + M
iOS Press Cmd + D (on Mac)
Expo CLI Press M in the terminal

🛠️Features in the Developer Menu


Once the menu is open, you get several useful options:

Feature Description
Reload Manually refresh your app (like hot reload)
Go to Home Exit app and return to the Expo Launcher
Debug JS Remotely Open a debugging session in Chrome
Enable/Disable Fast Refresh Automatically reload app when code changes
Performance Monitor Show real-time performance info (FPS, JS threads)
🌐 Remote JavaScript Debugging (via Chrome)

✅ How to Enable:

1. Open the Developer Menu.


2. Select "Debug JS Remotely".
3. A new tab opens in Google Chrome.

This tab becomes a debugging environment for your running app.

🧰 What You Can Do in Chrome DevTools:


Tool Usage
Console Tab View logs from console.log()
Network Tab Monitor API/network requests made by the app
Sources Tab Set breakpoints and inspect JavaScript code
Performance Tab Profile rendering and interaction performance

Example:
console.log("GoalInput rendered");

Will appear in:

 Terminal
 Chrome DevTools console (when remote debugging is active)

🧠 This is especially useful for inspecting backend calls, such as APIs, authentication, etc.

🛑 When It Gets Clunky

Remote debugging is powerful but not perfect:

 Sometimes logs don’t appear immediately.


 May require a manual reload (R) or app restart.
 Can slow down app performance during debugging sessions.
✅ How to Exit Remote Debugging
You can disable remote debugging:

 Go back to the Developer Menu.


 Choose "Stop Debugging" or "Disable Remote Debugging".

This returns your app to normal local runtime.

🔍 When & Why to Use Developer Tools


Scenario Use This Tool
Check why API data is not loading Network tab in Chrome
Validate state update flow Console logs or breakpoints
App freezes or is slow Performance Monitor
App doesn’t reload as expected Use manual Reload from Dev Menu
Need to trace logic execution Set breakpoints in DevTools Sources

🧠 Expert-Level Debugging Strategy (Best Practice)


1. Start with console.log():
o Quick and light debugging.
2. Open Developer Menu when needed.
o Access manual tools or force reloads.
3. Use Remote Debugging for:
o Network issues
o Advanced state inspection
4. Check performance only when you face lag or unresponsiveness.
5. Turn off remote debugging once you're done — to improve app speed.

📝 Summary
Tool Purpose Access
Metro CLI Shortcuts Reload, open emulators ? key in terminal
Developer Menu Debug UI, JS, performance M key or emulator shortcut
Remote JS Debugging Full Chrome DevTools Developer Menu → Debug JS
Console Logs Print messages in app flow console.log()
🧠 Deep Debugging with React Developer Tools in React Native
In previous sections, we discussed basic debugging (console.log) and remote debugging using
Chrome DevTools. Now, let’s dive into a more advanced and powerful method: using React
Developer Tools with React Native.

🔍 Why Use React DevTools?

React Developer Tools (DevTools) allow you to:

 Inspect the component tree (see how components are nested)


 View props and state in real-time
 Edit state/props on the fly and see live updates
 Debug complex state flows and prop drilling
 Understand the structure of your UI

💡 Unlike Chrome DevTools, React DevTools focus purely on React-specific debugging, making
them ideal for component-based inspection.

🚫 Browser Extension Does Not Work for React Native


The standard React DevTools browser extension does not work with React Native, because:

 It expects a DOM-based browser environment.


 React Native uses a native runtime, not the web.

Therefore, you need the standalone desktop version of React DevTools.

🛠️Installing React DevTools (Standalone)

Step 1: Open a new terminal

Keep your npm start / npx expo start process running in another terminal.
Step 2: Install DevTools globally
npm install -g react-devtools

 On macOS/Linux, you may need sudo:


 sudo npm install -g react-devtools

 On Windows, sudo is not needed.

This installs the standalone React DevTools CLI tool on your system.

▶️Running React DevTools


Once installed, run it in the terminal:

react-devtools

 This will open a standalone desktop window.


 This tool will try to connect to any running React Native instance with Remote Debugging
enabled.

🔗 Connecting DevTools to React Native App

Step 1: Go to your simulator/emulator

Step 2: Open the Developer Menu:


Platform Shortcut
Android Ctrl + M
iOS Cmd + D
Expo CLI Press M in terminal

Step 3: Enable Remote Debugging

Select:
✅ Debug Remote JS
✅ Now:

The DevTools will automatically connect to your running React Native app.

🧠 Note: Enabling remote debugging changes how the app is rendered (runs JS in a browser). This
might sometimes affect behavior like styles, especially background color issues.

🌳 Using React DevTools: Key Features


Once connected, here's what you can do:

Feature Description
Component Tree View the full nested tree of React components.
Inspect Components Click any component to see its props and state.
Live State Viewing See state updates in real-time as the app changes.
Manually change state values and instantly see how the app
Live State Editing
reacts.
Inspect Props Check what data is passed to each component.
Understand Component Helps in debugging conditional rendering, nested components,
Structure etc.

🧪 Example:

 Open the GoalInput component in the DevTools.


 Start typing into a text input.
 You will see:
o The state update live.
o You can click and edit the state manually — this updates the app instantly.

This is extremely useful for:

 Debugging form inputs


 Simulating user interactions
 Testing how your app responds to different state conditions without needing to modify code
🐛 Known Quirks & Caveats
Issue Explanation
Sometimes enabling remote JS debugging causes background color or
Color/style changes
layout to break temporarily.
Remote debugging and React DevTools may slow down your app — best
Performance impact
used only when needed.
Need to reload You may need to force reload (R) the app if DevTools does not connect or
sometimes reflect state properly.

✅ When to Use React DevTools


Situation Use DevTools?
You want to debug component structure ✅ Yes
Need to inspect state & props ✅ Yes
Debugging render logic or conditional UI ✅ Yes
Only testing a quick variable ❌ Prefer console.log
App is laggy or critical performance test ❌ Disable DevTools & Remote Debugging

🔄 Workflow Summary (Expert Practice)


1. Install & run DevTools using react-devtools
2. Open your app and enable Remote JS Debugging
3. Inspect your component tree
4. View/change props & state directly
5. Disable Remote Debugging when done to restore normal performance

🧠 Pro Tip for Experts:


Pair React DevTools with Redux DevTools or React Query DevTools (if using those libraries) for
even more visibility into global state and caching behavior.

📝 Summary Table
Tool Purpose Access
React DevTools Inspect React components, props, Install with npm install -g
Tool Purpose Access
(Standalone) state react-devtools
Enable Remote Debugging to
Developer Menu Emulator or press M in terminal
connect DevTools
Chrome DevTools Debug JS, network, console logs Opened via "Debug Remote JS"

You might also like