Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 71 ยท Quality

Common Pitfalls and Fixes

The React Native mistakes almost every team makes, with fixes: text outside Text, covered inputs, Android back, image sizes, background timers and stale closures.

Most React Native bugs are not exotic. They are the same dozen mistakes, made by every team, in every app, every year. Each one has a cause that is easy to understand once you have seen it, and a fix that takes a few lines. Learning them now saves you hours of staring at a red screen later.

This lesson walks through six of the most common ones, each as a before and after: strings outside <Text>, a keyboard that covers the input, the Android back button, images without sizes, timers that disagree with the clock once the app goes to the background, and stale closures. Two of them have live stand-ins you can run.

Read-only and stand-in. The real components need a phone, so the React Native code is in plain blocks. The TryIts use small stand-in components and a fake clock to reproduce the logic of each bug in a browser.

Pitfall 1: text outside <Text>

On the web you can put words inside any div. In React Native only <Text> can display text. A raw string inside a <View> has no native view that can draw it, so the app shows a red error: Text strings must be rendered within a <Text> component.

TSX
// Before: crashes
<View>Hello</View>

// After
<View>
  <Text>Hello</Text>
</View>

The sneakiest version is the && operator. When the left side is the number 0, the expression evaluates to 0, and React renders the number:

TSX
// Before: crashes when items.length is 0
<View>{items.length && <Text>You have items</Text>}</View>

// After: the left side is a real boolean
<View>{items.length > 0 && <Text>You have items</Text>}</View>

On the web a stray 0 just prints a zero. In React Native it is a crash. Make a habit of comparing (> 0) or using a ternary (items.length ? <List /> : null). The core components are explained in Core Components: View, Text, Image.

Pitfall 2: the keyboard covers the input

On a phone the keyboard takes up half the screen and slides over your layout. A login form with the password field near the bottom hides exactly the field the user is typing into.

The usual fix is a combination of two components (details in ScrollView and Keyboard Handling):

TSX
import { KeyboardAvoidingView, Platform, ScrollView } from 'react-native';

<KeyboardAvoidingView
  style={{ flex: 1 }}
  behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
  <ScrollView keyboardShouldPersistTaps="handled">
    {/* inputs and a submit button */}
  </ScrollView>
</KeyboardAvoidingView>

Why this works: KeyboardAvoidingView makes room on iOS, where the keyboard overlaps the app. ScrollView lets the user scroll the field into view. keyboardShouldPersistTaps="handled" fixes a second classic bug: without it, the first tap on a button only closes the keyboard and the press is swallowed.

Android often resizes the window for you, but that behavior depends on your app config and on whether the app draws edge to edge, so always test on a real Android phone and not only on iOS.

Pitfall 3: the Android back button

iOS has no back button; Android has a button or gesture, and users press it constantly. Navigation libraries handle it for screens. You run into trouble with things you built yourself: a bottom sheet that stays open while the screen behind it goes back, a "discard changes?" prompt that never appears, or an app that closes when the user only meant to dismiss a modal.

Register a handler while the sheet is open and return true to say "I handled it" (the full ordering rules are in Platform APIs):

TSX
useEffect(() => {
  if (!sheetOpen) return;
  const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
    setSheetOpen(false);
    return true;
  });
  return () => subscription.remove();
}, [sheetOpen]);

The effect only registers the handler while the sheet is open, and removes it afterwards. A handler that stays registered forever is its own bug: the back button would never leave the screen.

Pitfall 4: images without sizes

A web <img> loads and then takes its natural size. A React Native <Image> with a remote uri has no size until it loads, and React Native does not wait. With no width and height (or a flex layout that provides them) the image takes up 0 by 0 pixels and simply is not there.

TSX
// Before: invisible
<Image source={{ uri: 'https://example.com/photo.jpg' }} />

// After: explicit size, or a layout that gives one
<Image
  source={{ uri: 'https://example.com/photo.jpg' }}
  style={{ width: '100%', aspectRatio: 4 / 3 }}
  resizeMode="cover"
/>

Local images imported with require carry their size, so they do not have this problem.

The second image bug is memory. A phone decodes a picture into raw pixels, four bytes per pixel. A 4000 by 3000 photo is 12 million pixels, so it needs about 48 MB of memory even if you show it in a 100-point thumbnail. A list of such images can crash the app. Ask your server for a right-sized thumbnail instead of the original, and see Images, Icons and Media for caching and placeholders.

Pitfall 5: timers and the background

When the user switches to another app, your JavaScript may be paused or throttled by the operating system. A setInterval that adds one every second is not a clock: it only counts the ticks that actually ran.

If you build a countdown, a stopwatch or a "session expires in..." message, store the start time (or end time) and compute the remaining time from the real clock each tick. Use AppState to refresh the display when the app returns to the foreground.

TSX
const [endsAt] = useState(() => Date.now() + 60_000);
const [now, setNow] = useState(Date.now());

useEffect(() => {
  const id = setInterval(() => setNow(Date.now()), 1000);
  return () => clearInterval(id);
}, []);

const secondsLeft = Math.max(0, Math.round((endsAt - now) / 1000));

The interval only triggers re-renders. The truth comes from Date.now(). Always clear intervals in the effect cleanup (see Effect Cleanup), or timers keep running for screens that no longer exist.

Pitfall 6: stale closures

A function remembers the variables of the render in which it was created. If you start an interval or a listener once (empty dependency list) and read state inside it, it keeps reading the value from the first render forever:

TSX
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000); // count is always 0 here
  return () => clearInterval(id);
}, []);

There are two good fixes. Use the functional update form when the next state depends on the previous one: setCount((c) => c + 1). Or list the value in the dependency array so the effect restarts when it changes. For event handlers that must see fresh values but should not restart anything, see useEffectEvent. Mobile code is full of long-lived callbacks (timers, AppState and Linking listeners, WebSocket handlers), so this one bites often.

Six traps, six fixes

Text outside Text Wrap strings in Text; compare with > 0.
Hidden input KeyboardAvoidingView plus ScrollView.
Back button BackHandler, return true.
1 / 2

Stand-in: a before and after for pitfall 1

The real renderer is native, so this stand-in uses tiny View and Text components and a validate function that walks the tree the way React Native's renderer effectively does: strings and numbers are only allowed under a Text. Each case shows the problems it finds, or the rendered result when it is fine.

Strings must live inside Text

The second case fails because 0 && ... is 0, which is a number sitting in a View. Changing the check to items.length > 0 produces false, which React renders as nothing.

Stand-in: a stale closure with a fake clock

Real timers are slow to demonstrate, so this stand-in replaces setInterval with a fake clock: components register a callback, and the button calls every registered callback once. Both counters register their callback exactly once, with an empty dependency list. Only one of them avoids the stale value.

Stale closure vs functional update

After five ticks the buggy counter still says 1, because its callback always computes 0 + 1, while the fixed counter says 5. The functional form does not read count from the closure at all: React hands it the latest value.

Stand-in: ticks are not a clock

This plain-JavaScript simulation runs a 60-second countdown on a phone where the app is in the background from second 20 to second 40, and JavaScript timers do not run there. It compares counting ticks with reading the clock.

JS Countdown by ticks vs by timestamp

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The tick counter says 20 seconds are left when the real countdown ended. The clock-based version is right no matter how many ticks were skipped.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does {items.length && <Text>Items</Text>} crash when the list is empty?

    0 && x is 0, and React renders numbers. A number directly inside a View is not allowed. Use items.length > 0 so the result is false.
  2. 2. What does keyboardShouldPersistTaps="handled" fix?

    By default a tap outside a focused input dismisses the keyboard and is not delivered to the target. With handled, taps on pressable children still work.
  3. 3. A remote Image has no width or height in its style. What usually happens?

    React Native cannot know a remote image's size before it loads, so you must provide a size or a layout that gives one.
  4. 4. What is the most reliable way to build a countdown that survives the app being in the background?

    Timers can be paused or throttled in the background, but the clock keeps going. Compute from timestamps and use the interval only to refresh the display.
  5. 5. Which fix removes the stale value in setInterval(() => setCount(count + 1), 1000) inside an effect with []?

    The functional form receives the latest state from React, so the callback no longer depends on the value captured from the first render.

Summary

  • Strings and numbers belong inside <Text>; write items.length > 0 && ... instead of items.length && ....
  • Combine KeyboardAvoidingView and ScrollView (with keyboardShouldPersistTaps="handled") so inputs stay visible and buttons stay tappable; test Android on a device.
  • Custom overlays need a BackHandler handler that returns true and is removed when the overlay closes.
  • Remote images need explicit sizes, and photos should be resized by the server to protect memory.
  • Timers count ticks, not time: compute elapsed time from timestamps.
  • Long-lived callbacks capture old state: use functional updates or correct dependencies.

Next, take your app from your laptop to the stores in Builds with EAS and App Store Submission.