Sub topic 7
Using the Console and source links with a selected component
This chapter assumes you can read the Components tab and inspect props, state, and hooks. It also assumes you are comfortable typing expressions in the browser Console. The Components tab shows values, but it can't filter an array, compare two objects, or call a method. The Console can do all of that, and React Developer Tools connects the two. This chapter covers how.
What the selected component gives you
When you select a component in the Components tab, DevTools assigns it to a Console variable named $r. The variable is available in the Console of the same browser DevTools window, so you can switch panels without losing it.
What $r contains depends on the component type:
| Component type | What `$r` holds |
|---|---|
| Function component | An object with `props`, `type`, and (in current DevTools versions) `hooks` |
| Class component | The actual class instance, so `props`, `state`, `context`, and methods such as `setState` |
The type field is the component function or class itself. Evaluating $r.type in the Console prints the function, and you can click it to jump to its definition.
Here is a small component to practice on:
import { useState } from 'react';
export function Cart({ items, currency = 'USD' }) {
const [coupon, setCoupon] = useState('');
const total = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return (
<section>
<h2>Cart ({items.length})</h2>
<p>
Total: {total.toFixed(2)} {currency}
</p>
<input
value={coupon}
onChange={(event) => setCoupon(event.target.value)}
placeholder="Coupon"
/>
</section>
);
}Select Cart in the Components tab, open the Console, and try these expressions:
// In the Components tab, select Cart, then switch to the Console:
$r.props; // { items: [...], currency: 'USD' }
$r.props.items.length; // how many items the component received
$r.props.items.filter((i) => i.qty === 0); // find suspicious rows
$r.type.name; // 'Cart'
$r.hooks; // the hooks tree, if your DevTools version exposes itThe Components sidebar would show the same props, but the Console lets you query them. A filter like the third line answers "does any item have a quantity of zero?" in one step. In the sidebar you would have to expand every row.
Rules that trip people up
$r behaves like a pointer, so a few rules follow from that.
- It changes when you select something else. If you store a value you want to keep, copy it into your own variable:
const first = $r.props.items[0]. Variables declared withconstin the Console stay available until you reload the page. - It reflects the last render DevTools saw. After the app updates, select the component again (or click another component and come back) before you trust what
$rshows. - Props are read-only by contract.
$r.props.items.push(...)changes the array in place, but React does not know about it and nothing re-renders. You get a UI that disagrees with its data, which is a bug you introduced yourself. To change values and see the UI respond, use the live editing from the previous chapter, or callsetStateon a class instance. - Function components give you no setters. Hook state is visible in
$r.hooks, but thesetfunction fromuseStateis not exposed there. You can't callsetCouponfrom the Console. Edit the hook value in the sidebar instead. - Names depend on the build. In a minified production build,
$r.type.namecan be a single letter. The Console is most useful against a development build.
Keeping a value: store as global variable
Sometimes the value you want is nested, such as one object inside $r.props.items. In the Components sidebar, right-click a value and choose Store as global variable. DevTools then writes it to the Console and assigns it to a variable named $reactTemp0. The next one you store is $reactTemp1, and so on.
// After storing props.items[2] with "Store as global variable":
$reactTemp0; // the same object the component received
$reactTemp0.price * $reactTemp0.qty;This is useful when the same object appears in several places and you want to check whether it is the same reference or a copy. You can compare the stored value with a value from another component using ===. A mismatch is a common reason a memoized child re-renders. A later chapter covers that case.
Logging component data
The Components toolbar has a bug icon labeled Log this component data to the console. Clicking it prints the selected component's props, state, and hooks as plain objects, with a label naming the component. Use it when you want a snapshot of the data at one moment. $r always points at the current selection, so a logged object is a better record of how things looked before you changed something.
Source links
The toolbar also has a <> icon labeled View source for this element. It opens the component's definition in the browser's Sources panel. This saves time in a large codebase, because you go from a running component to its code without searching the project for the name.
Source links work through the same mechanism as any other browser debugging, so they depend on your build:
- In development, the Sources panel shows your original files if source maps are enabled, which most bundler dev servers do by default.
- With minified output and no source maps, the link opens compiled code. You can still read it, but variable names are mangled.
- Components wrapped in
memo,forwardRef, or a higher-order component can open the wrapper's file instead of the inner function. If the location looks wrong, check theRendered byentries in the sidebar and select the inner component.
You can also reach source through the Console. Evaluating $r.type prints the function, and right-clicking it in the Console offers Show function definition. This works even where the toolbar link misbehaves.
Functions inside props and hooks, such as onSelect, often have their own jump-to-definition option when you hover over or right-click them in the sidebar. This helps when a prop handler does the wrong thing and you need to find which function the parent actually passed.
Moving between the Elements panel and the Components tab
The browser's Elements panel and the Components tab are two views of the same page, and you can move between them in both directions.
- Select a DOM node in the Elements panel, then switch to the Components tab. DevTools selects the React component that rendered that node. This answers "which component draws this button?"
- With a component selected in the Components tab, click the eye icon (Inspect the matching DOM element). The Elements panel jumps to the node. The browser then sets its own variable
$0to that node. - In the Console,
$0is the DOM node and$ris the component, so you can compare them directly:$0.textContentagainst$r.props.label.
A worked example
Suppose the Cart heading says Cart (3) but the total looks too low.
- Select
Cartin the Components tab. - In the Console, run
$r.props.items.map((i) => [i.name, i.price, i.qty]). You see one row hasqty: '2', a string instead of a number. - Run
$r.props.items.reduce((s, i) => s + i.price * i.qty, 0). JavaScript multiplies the string by the price and converts it, so the sum here is right. Buttypeof $r.props.items[1].qtyreturns'string', which shows that the data is wrong at its source. Elsewhere,+on that string would concatenate instead of add. - Select the parent component, check its
Rendered byentry, and use View source to open the code that builds the items.
The fix belongs in the parent's data conversion. The Console showed you what was wrong, and the source link took you to where to change it.
Exercise
You selected a function component named Profile and ran $r.props.user in the Console. You then click a different component and run $r.props.user again. Why can the output change, and what should you do if you need to compare the two user objects afterward?
Show answer
$r always points at the component that is currently selected, so selecting another component changes what $r refers to. To compare the two objects, save each one while its component is selected, for example const userA = $r.props.user and later const userB = $r.props.user. Alternatively, right-click each value in the sidebar and choose "Store as global variable" to get $reactTemp0 and $reactTemp1. Then compare them with userA === userB to check whether they are the same reference, or compare their fields.
Exercise
The "View source" icon opens minified code with single-letter variable names. Name two things you can check or change to get readable source, and one way to reach a component's definition without using the toolbar icon.
Show answer
Check that you are running a development build and that source maps are enabled in your bundler configuration, because minified output without source maps produces unreadable source. To bypass the icon, evaluate $r.type in the Console and right-click the printed function to choose "Show function definition". You can also use the jump-to-definition option on a function value in the sidebar.