Debugging React

A React page is built from components (functions that return one part of the page). A component receives props (data from its parent) and keeps state (its own…

You click a small +1 button, and the 2,000-row table under it stutters too. The Elements panel only shows a pile of <div> and <li>. That panel can't tell you which component did the work, with which props, or why.

A React page is built from components: functions that return one part of the page, such as one row of a table. A component receives props (data sent by its parent component) and can keep state (data that belongs to the component itself and can change, such as a number of clicks). To render means React runs the component's function to calculate what it shows. When state changes, the component renders again (a re-render). So with React, you check the components: their props and state, and why they rendered again.

Think of a restaurant kitchen. The Elements panel only shows the plate already served (the DOM). React Developer Tools opens the kitchen door: which cook (component) made which part, with ingredients from the head chef (props) and what's in their own drawer (state). Its Profiler records which cooks worked on each order, including cooks who made the exact same dish again for no reason.

React Developer Tools

React Developer Tools is an extension (an add-on program) for the browser, from the Chrome Web Store or Firefox Add-ons. Once it's installed, DevTools gets two new tabs on pages that use React: Components and Profiler.

The app we check

This is the app in the Lab. App keeps two pieces of state: the number of clicks (clicks) and the list of goods (items, each with a name and a price).

function Item({ id, name, price }) {
  return <li>{name}: {price}</li>;
}

function List({ items }) {
  return <ul>{items.map((item) => <Item key={item.id} {...item} />)}</ul>;
}

function App() {
  const [clicks, setClicks] = useState(0);
  const [items, setItems] = useState([
    { id: 1, name: "Book", price: 50000 },
    { id: 2, name: "Pencil", price: 5000 },
  ]);

  return (
    <div>
      <button onClick={() => setClicks(clicks + 1)}>+1 ({clicks})</button>
      <List items={items} />
    </div>
  );
}

Before you record, guess: the props of List and the Items don't change at all. If you click +1 once, how many components render again? Only App, or all four (App, List and both Items)?

Profiler: who rendered, and why

  1. Open the Profiler tab, click the gear icon, then tick Record why each component rendered while profiling.
  2. Click the record button (the blue circle), click +1 once in the app, then stop the recording.
  3. Pick a commit, hold the mouse pointer over a component, and read Why did this render?

This is the recording of the app above, from page load to one click. The last column is that reason's name in the exercise's log:

Commit Component Why did this render? Written in the exercise's log
1 App This is the first time the component rendered. mount
1 List This is the first time the component rendered. mount
1 Item id 1 and id 2 This is the first time the component rendered. mount
2 App Hook 1 changed state
2 List The parent component rendered. parent
2 Item id 1 The parent component rendered. parent
2 Item id 2 The parent component rendered. parent

One click makes 4 components render, not just App. The basic rule: when a component renders, all its children (the components it shows) render too, even when their props are exactly the same. "Hook 1 changed" is DevTools' way of saying that the state from the first useState changed.

List and the two Items in commit 2 are wasted renders. The only reason is "The parent component rendered.", and their props and state are exactly the same as in the render before. So what they show is the same too. With two items you won't feel these wasted renders. With a 2,000-row table, every unrelated click can make the page stutter.

React.memo: skip the wasted renders

memo wraps a component. React then skips rendering that component when all its props are the same as in the render before. Here are Item and List wrapped in memo:

import { memo } from "react";

const Item = memo(function Item({ id, name, price }) {
  return <li>{name}: {price}</li>;
});

const List = memo(function List({ items }) {
  return <ul>{items.map((item) => <Item key={item.id} {...item} />)}</ul>;
});
Action Without memo With memo
Click +1 App, List, Item 1, Item 2 App only
Change the Pencil's price through setItems App, List, Item 1, Item 2 App, List (Props changed: items), Item 2 (Props changed: price)

Exercise: analysing a Profiler log

In the exercise, a Profiler log is ready as an array. Each entry looks like { component, duration, reason, props, state }. duration is how long the render took in milliseconds, and reason (the reason for the render) is one of mount, props, state, parent, hooks. The log has 11 entries: the mount (the first render), one click, then a second click. What you calculate, and the results:

What's calculated How Result
totalDuration the sum of every duration, rounded 49
byReason.mount how many mount entries 4
byReason.parent how many parent entries 5
slowestComponent add up duration per component: App 13, List 26, Item 10 List
findWastedRenders parent entries whose props and state equal an earlier entry of the same component Item,List
recommendMemo(log, 2) components with at least 2 wasted renders: List 2 times, Item 3 times Item,List

There are two Items (id 1 and id 2). That's why an Item render is wasted when its props and state equal those of any earlier Item entry, not just the Item entry right before it. Compare props and state with JSON.stringify(a) === JSON.stringify(b).

A classic bug: rendering without end

useEffect runs code (an effect) after a render. This code changes state inside useEffect:

const [count, setCount] = useState(0);

useEffect(() => {
  setCount(count + 1); // runs after every render, then triggers another render
}); // no dependency array

A dependency array is the array in the second argument of useEffect, holding the values the effect watches. An effect with no dependency array runs after every render. The effect changes state, the changed state triggers a render, and the render triggers the effect again, forever. In development mode (while the app is still being built), React prints this warning:

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

The fix: give it the right dependency array. [] means only once, on mount. [userId] means every time userId changes. Or, when the value can be calculated directly from props, don't keep it as state at all. If setCount(...) is called right in the component's body (not in a handler such as onClick, or in an effect), React stops it with the error Too many re-renders. React limits the number of renders to prevent an infinite loop.

🎯 More tricks for debugging React

⚠️ Wrong ideas about rendering in React

TL;DR: A React page is built from components (functions that return one part of the page). A component receives props (data from its parent) and keeps state (its own data that can change). Install the React Developer Tools extension. The Components tab shows the component tree with its props and hooks (such as useState), and you can edit them right there. The Profiler tab records which components rendered (run again by React) in each commit (one time React updates the screen) and why: turn on "Record why each component rendered while profiling." first. When a parent renders, all its children render too. A render whose reason is "The parent component rendered." with exactly the same props is a wasted render. memo skips a component whose props are the same (compared with Object.is), but loses to objects and functions made fresh on every render. A useEffect with no dependency array (the array of values it watches) that changes state makes renders without end. In the exercise: total duration 49, mount entries (first render) 4, parent entries (the parent rendered) 5, slowest component List, and the wasted renders are in Item and List.

⚡ Install React Developer Tools

Meaning: The Elements panel only shows HTML. A React page is built from components (functions that return one part of the page). To see each component's props (data from its parent) and state (its own data that can change), install the React Developer Tools browser extension. The Components tab shows the component tree with its props and hooks (such as useState). The Profiler tab records which components rendered (run again by React) and why.

⚡ The parent renders, its children follow

Write:

<button onClick={() => setClicks(clicks + 1)}>+1 ({clicks})</button>
<List items={items} />
Guess first: this code is in the App component. clicks is App's state, and List shows two Items. The props of List and the Items don't change at all. Click +1 once: how many components render again?

Four: App, List and both Items. When a parent renders, all its children render too, even when their props are exactly the same.

Meaning: Here the Profiler's reason for the List and Item renders is "The parent component rendered." When their props are also exactly the same, it is a wasted render: they show the same as before.

⚡ memo skips what didn't change

Write:

const Item = memo(function Item({ id, name, price }) {
  return <li>{name}: {price}</li>;
});

Meaning: memo wraps a component, here Item. React skips rendering that component when all its props are the same as in the render before. But an object or function made fresh on every render always counts as changed. Measure in the Profiler first, then add memo.

⚡ Rendering without end

Meaning: useEffect runs code (an effect) after a render. With no dependency array (the array in the second argument, holding the values it watches), the effect runs after every render. If the effect calls setState (a function that changes state, such as setCount), the changed state triggers a render, and the render triggers the effect again, forever. Give it the right dependency array, such as [] for only once on mount (the first render).

What you will learn