Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 71 ยท Quality

Debugging and Performance Profiling

Debug React Native apps with the dev menu, React DevTools, LogBox and the Hermes profiler, then hunt slow startup, big bundles and needless re-renders.

A phone app has more places to hide a bug than a web page. The problem might be in your JavaScript, in a native module, in the network, in the layout, or only in a release build. Good debugging is mostly knowing which tool answers which question. Good performance work is the same: measure first, change one thing, measure again.

This lesson tours the tools that ship with React Native and Expo, shows how to read what they tell you, and gives you a routine for the three most common complaints: "the app starts slowly", "the download is huge" and "the screen janks when I type". Debugging React itself is covered in Debugging React and Profiling React Apps; here we focus on what is different on a device.

Read-only and stand-in. Dev menus, DevTools and the Hermes profiler need a real device or simulator, so their commands are shown in plain code blocks. The TryIts at the end are stand-ins: a render counter and a bundle-size report that show the idea of the measurement with made-up numbers.

The developer menu

Every development build has a hidden dev menu. You open it differently per platform:

Where How to open it
Physical device Shake the phone
iOS Simulator Press Cmd+D
Android emulator Press Cmd+M (macOS) or Ctrl+M (Windows/Linux)
Terminal running Expo or Metro Press m to toggle the menu on the connected app

The menu lets you reload the JavaScript bundle, open the debugger, toggle the performance monitor and show an element inspector. The performance monitor draws two frame-rate numbers over your app: the UI frame rate (native side) and the JS frame rate (your JavaScript thread). If JS drops while UI stays at 60, your JavaScript is too busy. If UI drops, the native layout or drawing is the problem. The two threads are explained in How React Native Runs Your Code.

The element inspector works like "inspect element" in a browser: tap a view and you see its style, its size and the chain of components that created it. It is the quickest way to find out why a box is the wrong size.

Release builds have no dev menu, no LogBox and no debugger. Bugs that "only happen in production" are usually caused by that difference, so test a release build before you ship (see Builds with EAS and App Store Submission).

React Native DevTools

Press j in the terminal where npx expo start is running and the React Native DevTools open in a window on your computer. They connect to the Hermes engine inside your app and look like Chrome DevTools, with panels for:

  • Console: your console.log output, with objects you can expand. Because the app runs on the phone, the output travels over the connection to your computer.
  • Sources: set breakpoints, step through code, inspect variables. Source maps show your original TypeScript instead of the bundled output.
  • Components: the React tree with props, state and hooks. You can edit a value and watch the screen update. Turn on "Highlight updates when components render" to see boxes flash around every component that re-renders.
  • Profiler: record an interaction and see which components rendered, how long each took and, if you enable it, why each rendered (props changed, state changed, parent rendered).
  • Memory and Network panels: the available set depends on your React Native version. Network inspection arrived later than the others, so check your version's release notes before relying on it.

If your version does not show a Network panel, you can still log requests yourself with a small wrapper around fetch (a pattern you will build in Networking with fetch), or use a proxy tool such as Charles or Proxyman on the computer your phone is connected to.

Logging

console.log works in React Native, and its output appears in the terminal that runs Metro and in the React Native DevTools console. The other methods help organize it:

JavaScript
console.log('user', user);             // plain message
console.info('synced', count);         // informational
console.warn('slow request');          // yellow LogBox banner in development
console.error('failed', error);        // red LogBox error
console.table(items);                  // objects as a table in DevTools
console.group('checkout');             // indent related lines
console.log('step 1');
console.groupEnd();
console.time('parse'); parse(); console.timeEnd('parse');   // measure a duration

Habits that save time: log objects, not strings built with + (console.log('user', user), not 'user ' + user, which prints [object Object]); log before and after the suspicious line so you can see which side fails; and remove logs before release, because console.log in a hot path (a scroll handler, a list renderItem) slows the app, even in production builds. A common tool is a babel plugin that strips console.* from production bundles, or a small log wrapper that does nothing when __DEV__ is false:

JavaScript
export const log = (...args) => {
  if (__DEV__) console.log(...args);
};

For anything you want to keep, send structured events to a crash and analytics service (see Monitoring and Analytics) instead of relying on console.

A debugging routine

  1. Read the red box. The message and the first stack frame in your code usually name the problem.
  2. Reproduce it with the smallest steps, and note whether it happens on iOS, Android or both.
  3. Check the console for warnings that came before the error.
  4. Set a breakpoint in React Native DevTools (the debugger; statement also works) and inspect props and state.
  5. Inspect the layout with the element inspector in the developer menu if it is a visual bug.
  6. Reload, then clear caches (npx expo start --clear) when behavior does not match the code. Fast Refresh sometimes keeps stale state.
  7. Narrow it down by deleting code until the bug disappears. The last thing you removed is the cause.

Unhandled promise rejections

A promise that rejects with no .catch() (or an async function whose error is never caught) is an unhandled rejection. In development React Native shows it as a warning or red box ("Possible unhandled promise rejection"), and a release build may silently ignore it, leaving the user with a screen stuck on a spinner. The causes are almost always the same:

  • An async function called without await or .catch(), for example inside useEffect.
  • A fetch whose res.json() throws on a bad response.
  • A .then() chain with no final .catch().

The fixes: wrap awaited code in try/catch and set an error state; end promise chains with .catch(); and handle effects explicitly, since the callback of useEffect cannot itself be async.

JSX
useEffect(() => {
  let cancelled = false;
  async function load() {
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data = await res.json();
      if (!cancelled) setData(data);
    } catch (error) {
      if (!cancelled) setError(error.message);   // the rejection is handled here
    }
  }
  load();
  return () => { cancelled = true; };
}, [url]);
Finding and fixing an unhandled rejection

Run both cases. The first leaves the interface stuck on loading and adds one to the unhandled-rejection counter; the second ends in a visible error state the user can act on, such as a Retry button.

LogBox: warnings and errors on screen

In development, LogBox shows problems directly on the device. A yellow banner is a warning (from console.warn), a red full-screen box is an error. Tap a banner to see the message, the component stack and the code frame where it happened.

Read warnings; do not hide them. The common ones are real bugs: a missing key on list items, a state update on an unmounted component, a deprecated API. LogBox lets you silence a specific message when it comes from a library you cannot fix:

TSX
import { LogBox } from 'react-native';

// Only for known noise from a dependency, never for your own warnings.
LogBox.ignoreLogs(['Some third-party warning text']);

An ignored warning still goes to the console; LogBox only stops drawing the banner. Add a comment saying who owns the problem, otherwise you will forget it exists.

Measuring performance with Hermes

React Native runs your JavaScript on Hermes, an engine built for phones. It compiles your code to bytecode at build time, so the phone does not have to parse text on every launch. That is the biggest single reason startup is quick in release builds.

To find where time goes, use a profiler instead of guessing. The DevTools Profiler shows React work (renders). For raw JavaScript time, use the JavaScript profiler in the DevTools, which records a CPU sample every few milliseconds and shows a "flame chart" of which functions were running. Wide bars are slow. Look for:

  • one long task blocking the JS thread (a big JSON.parse, a sort of 10,000 items inside render),
  • the same cheap function called thousands of times,
  • work that runs on every keystroke but only needs to run once.

Profile a release-like build when you can. Development builds include extra checks and are much slower, so numbers from them are only good for comparing "before" and "after", not for absolute claims.

Startup time

Startup has three parts: the operating system launching the app, the native side loading React Native and Hermes, and your JavaScript running until the first screen draws. You control the third part the most:

  • Do less at the top level. Everything you import runs when the module loads. A file that imports a charting library, even if the chart is on the seventh screen, pays for it at launch. Metro's inline requires option delays running a module until the first time it is used. Expo's default Metro config already enables it; check yours if you use a custom one.
  • Defer non-essential work. Fetching feature flags, warming caches and initializing analytics can wait until after the first screen is visible.
  • Keep the splash screen honest. Hide it when the first meaningful screen is ready, not before and not much later. Showing an empty white screen after the splash feels slower than a splash that lasts 200 ms longer.
  • Measure. Log a timestamp when the entry file starts and another when the first screen mounts, and compare builds.

Bundle size

Two sizes matter: the JavaScript bundle (what Hermes loads) and the download from the store (JavaScript, images, fonts and native code together). To see what is inside the JavaScript bundle, export it and look at a visual map of its modules:

Terminal
# Create a production bundle and a source map
npx expo export --platform ios --dump-sourcemap

# Explore what is in it (Expo's bundle visualizer)
EXPO_ATLAS=true npx expo start

Typical findings are always the same: a date library with every locale, a whole utility library imported for one function, an icon set with thousands of icons used for six, and images far bigger than the screen they appear on. Fixes are equally boring: import single functions (lodash/debounce instead of lodash), swap heavy libraries for small ones, ship only the icons you use, and compress images.

Pick the tool for the question

Dev menu Reload, inspector, frame-rate monitor.
DevTools Console, breakpoints, components, profiler.
LogBox Warnings and errors on the device.
CPU profile Which function ate the time.
1 / 2

Hunting needless re-renders

A component re-renders when its state changes, when its parent renders, or when a context it reads changes. Re-rendering is cheap when the output is small, and a problem when a screen re-renders hundreds of rows on every keystroke. The routine is:

  1. Turn on Highlight updates in the Components panel and type into an input. If the whole list flashes, you found it.
  2. Record a Profiler session and turn on "why did this render".
  3. Fix the cause: move state down so fewer components depend on it, pass stable props, wrap expensive pure rows in memo, and use useCallback or useMemo only where a memoized child receives that value (see useMemo and useCallback and memo).
  4. For long lists, the biggest win is the list component itself, covered in Fast Lists: Virtualization and Tuning.

Do not add memo everywhere. Memoization has a cost and only pays off for components that are expensive and re-render with unchanged props.

Stand-in: a render counter

This TryIt is not the DevTools Profiler. It is a tiny counter that records every time a row commits. Both lists get the same, never-changing props. Press the button three times: the plain rows re-render every time because their parent did, and the memo rows render once.

Counting renders: plain rows vs memo rows

After three presses the log reads "plain = 12, memo = 3": three rows each rendered once on mount, then each press made all three plain rows render again (3 + 3 x 3 = 12) while the memo rows stayed at 3. In a real app the DevTools Profiler shows the same story with durations attached.

Stand-in: a bundle-size report

Real tools such as Expo Atlas draw a treemap. This stand-in makes the same point with a sorted table and invented sizes: a few heavy modules dominate the total, and the fixes are small import changes.

Which modules dominate the bundle?

Before the fixes the total is 1,431 KB and the "moment" module alone is about a fifth of it; after swapping three imports it drops to 876 KB and passes the budget. A size budget checked in CI (fail the build if the bundle grows by more than a set amount) stops the problem coming back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The performance monitor shows the UI frame rate at 60 but the JS frame rate dropping to 10 while you type. Where is the problem most likely?

    The JS frame rate measures your JavaScript thread. If it drops while the UI thread stays smooth, something in JS (often rendering too much) is the bottleneck.
  2. 2. Why should you be careful when judging performance from a development build?

    Dev mode adds warnings, validation and unoptimized code. Use it to compare before and after, and confirm important numbers on a release build.
  3. 3. What does LogBox.ignoreLogs do?

    It only hides the banner. Use it for known third-party noise, never to hide warnings from your own code.
  4. 4. Which change most directly reduces the size of the JavaScript bundle?

    Bundle size depends on which code is included. Importing only what you use (and replacing heavy libraries with small ones) removes code from the bundle.

Summary

  • The dev menu gives you reload, the element inspector and a UI/JS frame-rate monitor; release builds have none of it.
  • React Native DevTools (press j) offer a console, breakpoints, the component tree with highlight-updates and a profiler that can say why a component rendered.
  • LogBox shows warnings (yellow) and errors (red); read warnings and only ignore known third-party noise.
  • Hermes compiles to bytecode, which helps startup; defer imports and non-essential work to make the first screen appear sooner.
  • Inspect the bundle with an analyzer, fix the few big offenders and set a size budget.
  • Measure first, change one thing, measure again, preferably on a release-like build.

Next, protect your users and your backend in Mobile App Security.