Skip to content

Lesson 35 of 37React at scale

Debugging React Apps

A routine and a toolkit for React bugs: DevTools and the Profiler, StrictMode, stale closures, effect loops, hydration errors, minified errors and production reporting.

18 min read0/4 questions

A ticket lands on Monday: "The live viewer count on the dashboard gets stuck at 1." On Tuesday another one: "Checkout page shows a blank screen for some users, console says Minified React error #418." Neither reproduces on your machine on the first try. This is most of the job once you are past tutorials: not writing new components, but working out why existing ones behave wrongly, sometimes only in production, sometimes only for some users. Engineers who are fast at it are not guessing faster. They know where each kind of React bug lives, which tool shows it, and what the error messages actually mean.

Where React bugs live

You learned in How Rendering Works that every update goes through trigger, render, commit, and that effects run after the commit. Almost every React bug belongs to one of those phases, and naming the phase tells you which tool to open.

Which phase is the bug in?
Trigger: setState, props, contextTriggersetState, props, contextRender: your component runsRenderyour component runsCommit: DOM updatedCommitDOM updatedEffects: after paintEffectsafter paintNo re-render: same object passedNo re-rendersame object passedWrong output: props, state, keysWrong outputprops, state, keysHydration error: server vs client HTMLHydration errorserver vs client HTMLLoops, stale values: deps, closuresLoops, stale valuesdeps, closuressetState in effect

Nothing happens on click? The update may never have triggered a render. Mutating an array and passing the same reference to setState is the classic cause.

1/4

The routine is the one from Errors and debugging, with React vocabulary: reproduce it reliably, read the full error, locate the component and the phase, form one hypothesis and test it, make the smallest fix, then add a regression test so it stays fixed.

React DevTools: inspect, do not guess

The React DevTools browser extension adds two panels.

Components shows the component tree as React sees it, not the DOM. Select a component (or use the picker and click on the page) to see:

  • its props, state and hooks, with custom hooks shown by name, so useCart appears as a group with its inner state,
  • the owner chain ("rendered by"), which answers "who passed this prop?" faster than searching the code,
  • a link to the component's source.

You can edit state and props in place. If changing status to "error" in the panel shows the right error UI, the rendering is fine and the bug is in whatever sets status. The selected component is also available as $r in the browser console. There are buttons to force a component into its Suspense fallback or its error boundary, which is the fastest way to check loading and error states nobody ever sees on a fast laptop.

In the DevTools settings, Highlight updates when components render flashes an outline around everything that re-renders. Type one character into a search box and watch half the page flash, and you have found your performance bug before opening the Profiler.

Profiler records commits while you use the app. The flamegraph shows each commit's components, colored by how long they took, with grey for components that did not render. Turn on Record why each component rendered while profiling and hovering a component tells you "Props changed: onSelect" or "Hook 2 changed". That one setting answers most "why does this re-render?" questions. Components the React Compiler optimized carry a small Memo badge in the tree, so you can see at a glance what was memoized automatically.

StrictMode breaks things on purpose

<StrictMode> wraps most apps created by Vite or a framework. In development only, it runs certain code twice to surface bugs that would otherwise appear rarely and randomly:

  • Your component function bodies, useState and useMemo initializers, reducers and state updater functions are called twice. React 19 reuses the first call's memoized results for useMemo and useCallback in the second call, but the rest of your code still runs twice.
  • Every effect runs setup, cleanup, setup when the component first mounts, as if it mounted, unmounted and mounted again.
  • React 19 does the same for ref callbacks: attach, detach, attach.
One component mounting under StrictMode in development
ReactComponentEffectrenderrender againsetupcleanupsetup again

First call of your component function.

1/5
Predict the outputJavaScript

In development, inside <StrictMode>, this component mounts once. What does the console show, in order? (Count dimmed logs too.)

function Feed() {
console.log("render");
useEffect(() => {
  console.log("subscribe");
  return () => console.log("unsubscribe");
}, []);
return null;
}
Need a nudge? Hints walk you through it.

The bugs StrictMode finds are real ones. A render that pushes to a module-level array, an updater function that sends an analytics event, an effect that subscribes and never unsubscribes. The wrong fix is removing <StrictMode> or adding a "has run" ref to block the second setup. The right fix is making setup and cleanup symmetrical. The previews on this site use React's production build, so StrictMode does nothing in them. Try the example above in a local Vite project to see the double calls.

The usual suspects

Most React bugs you will fix at work are one of a handful. Two of them are running below. Watch the stuck counter and the list that will not update, then read the code.

ReactTwoClassicBugs.tsx
import { useEffect, useState } from "react"; function StaleCounter() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount(count + 1), 500); return () => clearInterval(id); }, []); return <p>Stale closure: {count}</p>;} function FixedCounter() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount((c) => c + 1), 500); return () => clearInterval(id); }, []); return <p>Updater function: {count}</p>;} function MutatingList() { const [items, setItems] = useState(["a"]); return ( <p> Mutated: {items.join(", ")}{" "} <button onClick={() => { items.push("x"); setItems(items); console.log("array now has", items.length, "items, screen did not update"); }} > Add (bug) </button>{" "} <button onClick={() => setItems([...items, "y"])}>Add (fixed)</button> </p> );} export default function App() { return ( <div> <StaleCounter /> <FixedCounter /> <MutatingList /> </div> );}

Stale closures. The interval callback was created in the first render, where count is 0. It sets 0 + 1 forever, so the counter sticks at 1. That is the Monday ticket. Fix it with an updater function, by adding the dependency, or with useEffectEvent when the value is read but should not restart the effect.

State mutation. items.push("x") changes the existing array, and setItems(items) passes the same reference. React compares with Object.is, sees no change and skips the render. Click "Add (bug)" twice, then "Add (fixed)", and the hidden x items suddenly appear, because the copy contains them. Bugs that "fix themselves on the next unrelated update" are almost always mutation.

Effect loops. An effect that sets state which is also its dependency, or that depends on an object or array created during render, runs after every render forever. In development React logs Maximum update depth exceeded. Find which dependency changes every time (the Profiler's "why did this render" helps), then derive the value during render, move the object inside the effect, or depend on a primitive like user.id instead of user.

Keys. Index keys on a list whose items can be inserted, removed or reordered attach state to the wrong row: you delete the second item and the third row's half-typed input appears in its place. key={Math.random()} is worse: every render remounts every row, so inputs lose focus on each keystroke. Lists and keys covers the rules. Use a stable id from the data.

Hydration mismatch. With server rendering, the client's first render must produce the same HTML as the server. Common causes: new Date() or Math.random() in render, typeof window !== "undefined" branches, formatting dates with the user's locale or time zone, invalid HTML such as a <div> inside a <p>, and browser extensions that edit the page before React loads. React 19 reports one error with a diff of server and client output, which usually points straight at the culprit. Fix it by rendering the same thing on both sides first and switching to browser-only output after hydration, or for one unavoidable text node such as a timestamp, suppressHydrationWarning. React 19.3 also added a browser() helper in react-dom for this situation; check the docs for how it fits your framework. Dates, times and Intl covers the date side in depth.

Match the pairs0/5 matched

Match each error message to its most likely cause.

Choose an item, then its match on the other side.

Minified errors and source maps

In development, React's errors are long and helpful. Production builds strip the text to keep the bundle small, and you get something like Minified React error #418; visit https://react.dev/errors/418 for the full message. Open that URL. It shows the full message, filled in with the arguments from the query string. Click the button below to see one for real, since this preview runs the production build.

ReactMinifiedError.tsx
import { useState } from "react"; const user = { id: 7, name: "Ana" }; export default function App() { const [showBug, setShowBug] = useState(false); return ( <div> <button onClick={() => setShowBug(true)}>Render the bug</button> {showBug && <p>Signed in as {user}</p>} </div> );}

Error #31 is "Objects are not valid as a React child", and the URL carries object with keys {id, name}, which tells you exactly what was rendered. In a typed project TypeScript would have caught this; the preview strips types without checking them.

The stack trace in production is the other problem. It points at index-4f2a91.js:1:48213, one line of minified code. Source maps map those positions back to your source files. The standard setup is to generate them at build time, upload them to your error tracker as part of the deploy, and not serve them publicly (many bundlers call this "hidden" source maps). Tag every release with the commit so an error can be matched with the exact code that threw it.

Performance bugs

"It feels slow" is a bug too, and Performance taught the first rule: measure first. The React tools for it:

  • The Profiler shows which components rendered in each commit and why. Look for big subtrees re-rendering because of one unstable prop or a context value that is a new object every render.
  • Performance Tracks (since React 19.2) add React's own tracks to the Chrome DevTools Performance panel in development and profiling builds. You see scheduler work by priority next to the browser's main thread, so you can tell whether a slow interaction was React rendering, your effects, or layout and paint.
  • The React Compiler memoizes components automatically, but it skips any component that breaks the Rules of React. The eslint-plugin-react-hooks recommended preset reports those violations, so a component that is mysteriously not memoized usually has a lint error waiting for you. Fix the violation instead of adding useMemo by hand.
Quick check
A search page re-renders the whole results list on every keystroke. The Profiler says the list rendered because 'Props changed: filters'. The parent creates filters as { q, sort } in its body. What is the most likely fix?
Need a nudge? A hint rules out a wrong answer.

Debugging in production

Some bugs only happen to real users on real devices. You need the app to report them.

Error boundaries catch render errors in a subtree and show fallback UI instead of a blank page. Error Boundaries and Resilient UI covers them in depth. For reporting, React 19's createRoot takes three callbacks: onCaughtError (an error boundary caught it), onUncaughtError (nothing caught it, the app unmounted) and onRecoverableError (React recovered on its own, for example after a hydration mismatch). Error trackers plug into these:

main.tsx
import * as Sentry from "@sentry/react";
import { createRoot } from "react-dom/client";
 
Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN, release: import.meta.env.VITE_COMMIT_SHA });
 
createRoot(document.getElementById("root")!, {
  onUncaughtError: Sentry.reactErrorHandler(),
  onCaughtError: Sentry.reactErrorHandler(),
  onRecoverableError: Sentry.reactErrorHandler(),
}).render(<App />);

Session replay tools record a reconstruction of what the user saw and clicked before the error, which turns "blank screen for some users" into "users on Safari who opened checkout from an email link". Replay records user data, so mask text and inputs by default and check it with whoever owns privacy at your company. Breadcrumbs (the clicks, navigations and requests before an error) and the release tag usually give you a reproduction within minutes.

Put it in order5 steps

A bug is reported only in production. Put a sensible debugging routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Debugging is where the whole course meets: a real bug can live in state, an effect, rendering or the network, and you now know how each one works. Next, Project: A Gym Workout Log has you build a small app from scratch that uses all of it.

Key terms
React DevTools
A browser extension with a Components panel for inspecting props, state and hooks, and a Profiler for recording renders.
Profiler flamegraph
A chart of one commit showing which components rendered and how long they took, with grey for those that did not render.
StrictMode
A development-only wrapper that double-calls render logic and runs effect and ref setup, cleanup and setup again to expose impure code and missing cleanups.
stale closure
A callback that captured values from an old render and keeps using them, such as an interval that always sees count as 0.
hydration mismatch
When the client's first render differs from the server HTML, making React report an error and re-render on the client.
minified error
A production React error reduced to a number with a react.dev/errors link that shows the full message.
source map
A file that maps positions in minified production code back to the original source, used by error trackers.