Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 132 ยท Testing and Quality

Debugging React Apps

Learn a repeatable way to debug React. Read error messages and stacks, understand StrictMode warnings, log renders, use DevTools, and fix the most common bugs.

Everybody ships bugs. The difference between a beginner and a professional is not that the professional writes fewer of them. It is that the professional has a method: read the message, form a guess, make the problem smaller, test the guess, and only then change code. Random edits ("let me add a useEffect and see") turn a ten-minute bug into a two-hour one.

React makes this easier than most frameworks, because in development mode it checks your code and tells you in plain English what is wrong. The skill is reading those messages. This lesson shows the real messages React 19 prints for the ten or so mistakes that cause most bugs, explains why StrictMode runs your code twice, shows tools for seeing what a component is doing, and ends with a catalogue of common mistakes and their fixes. It pairs with Testing React Components, which keeps bugs from coming back, and Rules of Hooks.

Our editor loads React's development build, which is why you see these warnings here. Production builds strip most of them out and replace long messages with a short error code, so always debug in development first.

A debugging method

Use the same five steps every time.

  1. Reproduce. Find the smallest sequence of clicks that always shows the bug. If you cannot reproduce it, you cannot know when it is fixed.
  2. Read the message. The first error in the console is usually the real one; later ones are often side effects. Read the whole sentence. React's messages are written to be useful.
  3. Locate. Use the stack trace or component name to find the file and line. Add console.log where you doubt your assumption.
  4. Shrink. Remove code until the bug disappears, then put back the last piece. Or copy the component into a tiny sandbox like this site's editor.
  5. Fix the cause, then test. Fix why it happened, not only what you saw. Then add a test so it cannot return.

Most React bugs fall into three families: the component crashes while rendering (you get an error), React warns but keeps going (you get a warning), or nothing is reported but the screen is wrong (stale or missing updates). Each needs a different approach, so let us take them in order.

Reading error messages

When a component throws during rendering, React shows the error and, without an error boundary, unmounts the whole tree (a blank page). The message has two parts: what went wrong, and a stack that says where.

A render crash (fails on purpose)

The page stays empty and the console shows TypeError: Cannot read properties of undefined (reading 'first'), followed by a stack whose first line of your code is at Profile. Read it from right to left: we tried to read .first (the property) of something that is undefined. That something is user.name, because the object we passed has an id but no name. The stack tells us the crash happened inside Profile, and your editor's link takes you to the line.

The fix depends on the cause. Maybe the data should have a name (fix the caller), maybe the data is still loading (render a loading state first), or maybe name really is optional, in which case use optional chaining: user.name?.first ?? 'Unknown'. Do not sprinkle ?. everywhere just to silence the error. Decide first whether the missing value is legal.

Here are other render errors you will meet. Each message below was copied from a real run in this editor.

Message (shortened) What it means Typical fix
Objects are not valid as a React child (found: object with keys {name}) You wrote where person is an object Render a field, {person.name}, or map an array of objects to elements
Too many re-renders. React limits the number of renders to prevent an infinite loop. You called setState during render, for example setN(n + 1) in the body Move the update into an event handler or an effect with the right dependencies
Rendered more hooks than during the previous render. A hook is behind an if, a loop or an early return Call hooks at the top level, always in the same order
The style prop expects a mapping from style properties to values, not a string. You wrote style="color:red" Use an object: style={{ color: 'red' }}

A component with a missing return (a function with braces that never returns anything) does not crash in React 19, it just renders nothing, so check braces and returns first when a brand new component stays blank.

Component stacks

A plain JavaScript stack lists functions, many of which belong to React itself. In development React also attaches a component stack to its warnings: a list like "in Profile, in App" showing which components were being rendered. In a browser console you see it under the warning text, with file and line when source maps are on. Read it from the top: the first entry is the component that triggered the warning, and the rest are its parents, so you can tell which of your 40 Button usages is the guilty one.

If you want a screen that does not go blank in production, wrap risky parts in an error boundary and log the error to a monitoring service.

Warnings: React keeps going but tells you

Warnings do not stop the app, which makes them easy to ignore. Do not. Each one is a bug waiting for the right data.

The missing key warning (fails on purpose)

The list renders, but the console reports Each child in a list should have a unique "key" prop. The page looks fine today. The problem appears when the list reorders or an item is removed in the middle: without a stable key, React matches items by position and state or input text jumps to the wrong row. Fix it with a stable identity from your data, such as key={fruit.id}. Using the array index is only safe for static lists that never reorder. See Lists and Keys.

Other warnings you will see often (all verified in this editor):

  • You provided a value prop to a form field without an onChange handler. This will render a read-only field. Use onChange with state, defaultValue for an uncontrolled field, or readOnly. See Forms and Inputs.
  • Invalid DOM property class. Did you mean className? and Invalid event handler property onclick. Did you mean onClick? You wrote HTML attribute names. JSX uses the DOM property names (JSX Basics).

Hooks errors

Hooks remember their values by call order. React does not know the names of your useState calls; it knows "the first one, the second one". If a hook sometimes runs and sometimes does not, the order changes and React loses track.

A hook behind an if (fails on purpose)

The first render is fine (one hook). Click the button and the second render calls two hooks. React stops with Rendered more hooks than during the previous render. and, just before, warns React has detected a change in the order of Hooks called by .... (Our console panel prints the %s placeholder where a browser console would substitute the component name Panel.) The fix is to call every hook on every render and put the condition inside or after the hooks. Install the ESLint plugin eslint-plugin-react-hooks to catch this before running; see Linting, Formatting and Code Quality.

StrictMode: running your code twice

<StrictMode> is a development-only wrapper that deliberately makes bugs louder. It does two things in React 19:

  • It renders every component twice (the second result is thrown away). A pure component gives the same output both times; a component that mutates something outside itself shows the difference.
  • It runs each effect's setup, then cleanup, then setup again once on mount. That simulates a component being unmounted and remounted, which can really happen (for example with <Activity> hiding and restoring a screen).

Neither happens in production. Wrap the app in StrictMode from the first day and read the log:

What StrictMode does to renders and effects

On load the log reads:

TEXT
render #1 (room general)
render #2 (room general)
effect: connect to general
cleanup: disconnect from general
effect: connect to general

Two renders for one mount, and an effect that connects, disconnects and connects again. After you press the button you get render #3 (room music) and render #4 (room music), then cleanup: disconnect from general and effect: connect to music. The extra cleanup and setup at mount happen only once; later updates run each effect once.

This is useful, not annoying. If your effect had no cleanup, you would now have two open connections, and the log would show a connect without a matching disconnect. A double render also exposes a component that modifies a variable declared outside it (the renderCount counter above is exactly such a bad habit; it is fine here only for demonstration). Whenever you see something running twice in development, ask "what would break if it ran twice?" and fix that. Never remove StrictMode to hide the symptom. See Effect Cleanup and Keeping Components Pure.

Bugs without errors: the screen is wrong

These are the hardest, because nothing in the console helps. Two causes make up most of them: mutating state, and stale closures.

Mutation and stale closures

Try it. Add (mutate) pushes onto the same array and passes the same array back to setItems. React compares the new state with the old using Object.is; it is the same object, so React assumes nothing changed and does not re-render. The console says the array has two items, yet the screen still shows a. Press the unrelated counter and suddenly the screen catches up and shows a, item 1, item 2, because that button caused a render that read the already mutated array. Add (copy) builds a new array and updates immediately. The rule: never change state in place; always give React a new object or array (Objects and Arrays in State).

The stale ticker is a stale closure. The effect has an empty dependency array, so the callback it created on the first render lives forever, and in that render count is 0. The log prints stale tick 1 sees count 0, stale tick 2 sees count 0 and stale tick 3 sees count 0, and setCount(0 + 1) runs every time, so the display sticks at Stale ticker: 1. The fresh ticker uses the updater form setCount((c) => c + 1), which does not need to read count from the closure, and it climbs steadily. Two fixes work: list count in the dependencies (the interval restarts each time), or use the updater function. The ESLint rule react-hooks/exhaustive-deps warns about exactly this. More in Effect Dependencies.

Seeing what a component does

When the screen is wrong and you do not know why, add eyes to the component.

Log renders

A render log answers "did this component re-render, and why?" This hook compares the props from the previous render:

A render log with changed props

The first line is Badge render #1. After each click on Increment or Tick you get Badge render #2 changed: onPing, then #3, and so on. Badge is wrapped in memo, yet it still re-renders, and the log names the culprit: the inline onPing arrow function is a new function every time App renders, so the memo comparison fails. Stabilize it with useCallback or let the React Compiler do so, and the log will go quiet. The ref writes inside the hook are fine in temporary debugging code; remove the hook when you are done. More tools are in Profiling and Debugging Performance.

useDebugValue

The same example has a custom hook with useDebugValue(count, (value) => 'count is ' + value). This call does nothing visible in the page. It adds a label that React DevTools shows next to the hook in the Components panel, so a custom hook such as useOnlineStatus can show Online instead of an opaque set of internals. The second argument is an optional formatter that is only called when DevTools is open, which is helpful if formatting is expensive. Use it sparingly, mostly in shared hooks and libraries.

React DevTools (read-only)

React DevTools is a browser extension (Chrome, Edge, Firefox) and also available as a standalone app. It cannot run inside our sandboxed editor, so use it in your own project:

  • Components tab. Browse the tree, select a component and see its props, state, hooks (with useDebugValue labels) and the context it reads. You can edit props and state live to try a theory without touching code, and right-click to jump to source.
  • Highlight updates. In the settings enable Highlight updates when components render to watch rectangles flash on every re-render. A whole page flashing on every keystroke is an easy clue.
  • Profiler tab. Records commits and answers "why did this render?" (Profiling).
  • Search by name to find all instances of a component, and use the "suspend" and "inspect the matching DOM element" buttons to connect the tree and the page.

Standard browser tools matter too: the Sources panel breakpoints (and the debugger; statement, which pauses when DevTools is open), "Pause on caught exceptions", the Network tab for data problems and the Elements tab to check what ended up in the DOM. Remember that a console.log of an object shows the object's current state when you expand it, not its state when it was logged; log a copy (JSON.stringify(obj)) to freeze it.

A catalogue of common mistakes

Symptom Likely cause Fix
Click does nothing, console says the array/object changed Mutating state Copy: [...items, x], { ...user, name }
onClick runs immediately on load onClick={doIt()} calls the function Pass a function: onClick={doIt} or onClick={() => doIt(id)}
A number 0 appears on screen {count && <List />} renders 0 Use {count > 0 && <List />} or a ternary
State seems one step behind after setCount Reading state right after setting it (it is a snapshot) Use the new value in a variable, or an updater function
Input loses focus on every keystroke A component is defined inside another component, so it is a new type each render Move the definition to module level
Input text jumps to another item Index used as key in a reorderable list Use a stable id as key
Effect runs forever Object or function created in render listed as a dependency, or the effect sets the state it depends on Move the value inside the effect, use primitives, or derive during render
Old data shows after a fast navigation Race between two requests Ignore outdated results in the cleanup function (Data Fetching)
Event handler sees old value Stale closure Updater function, correct dependencies or useEffectEvent
Cannot update a component while rendering a different component Calling a parent's setter during render Do it in an event handler or effect
Works in dev, breaks in production Code relies on StrictMode behaviour, minification or env variables Test the production build (npm run build and preview it)

One habit prevents many of these: derive instead of sync. If a value can be computed from props and state during render, compute it; do not copy it into more state and then try to keep the two in step (You Might Not Need an Effect).

When you are stuck

  • Bisect. Comment out half the component. Is the bug still there? Repeat with the half that keeps it.
  • Make a minimal reproduction. Paste the component into a fresh project or a TryIt with fake data. Half the time you find the bug while doing it; the other half you have a perfect question for a colleague or a bug report.
  • Check the data first. Log the props at the top of the component. Most "React bugs" are wrong data arriving from somewhere else.
  • Rule out your tools. Hard refresh, restart the dev server, check that you are editing the file the browser actually loads.
  • Explain the problem aloud (rubber duck debugging). Putting your assumptions into sentences exposes the false one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component crashes with Cannot read properties of undefined (reading 'first'). Which reading is right?

    The part in parentheses is the property being read. The value it was read from is undefined, for example user.name when name was never set.
  2. 2. In the StrictMode demo, why does the log show connect, cleanup, connect on the first mount?

    StrictMode simulates a remount in development only. A correct effect with a cleanup function behaves the same either way, and a missing cleanup shows up as a leaked connection.
  3. 3. Why did the screen not change after items.push(...) followed by setItems(items)?

    React compares old and new state with Object.is. The same array reference means no change. Create a new array with the spread operator instead.
  4. 4. The ticker with setCount(count + 1) in an effect with [] stays at 1. What is the best fix?

    The interval callback captured count as 0 on the first render. The updater form reads the latest state, so no stale value is involved.
  5. 5. What does useDebugValue do?

    useDebugValue only annotates a hook for DevTools. Nothing changes in your UI.

Summary

  • Debug with a method: reproduce, read the message, locate, shrink, fix the cause and add a test.
  • Read errors right to left and use the stack to find the component; warnings are bugs that have not struck yet.
  • Know the classic messages: missing keys, objects as children, too many re-renders, changed hook order, string styles, read-only inputs.
  • StrictMode renders twice and runs effect setup, cleanup, setup on mount, in development only, to reveal impure renders and missing cleanups.
  • Silent wrong-screen bugs are usually mutated state or stale closures; copy state and use updater functions.
  • Use render logs, useDebugValue, React DevTools and browser breakpoints to see what a component does.
  • When stuck, bisect, build a minimal reproduction and check the data first.

Next: Linting, Formatting and Code Quality