Debugging React 101 - Getting started
William Henshaw
Staff Software Engineer | Frontend Development | User Experience | Innovation
React provides a set of valuable tools to help us debug and optimize our applications.
But where should we start? The first step is to download the React Developer Tools extension for Google Chrome.
After that, launch your React application in the browser. In this example, we have a simple app to keep track of a list of classic books I'm reading.
Open Chrome DevTools and click on the "Components" tab, which has the React symbol next to it.
Here, you'll see the component tree of your application.
While this book-tracking app is simple, as your application grows over time, the ability to search for components will become incredibly useful.
On the right-hand side, things get even more interesting. When you select an individual component, this section populates with information specific to that component.
A nice touch is that if you set a key on a component, it will display a label next to the component's name at the top. In this case, the key is the book title.
Below that, you'll find the "props" section, which provides detailed information about the component's props.
领英推荐
export function Book({ title, author, yearPublished }) {
const [hasRead, setHasRead] = useState(false);
return (
<tr key={title}>
<td>{title}</td>
<td>{author}</td>
<td>{yearPublished}</td>
.....
Below the props section, you'll find information about the hooks used in the current component. In this simple example, we only have a single useState hook in use.
Nevertheless, it shows the current value of the hook.
To the left, you'll see a small wand icon. Hovering over it gives you the option to "parse hook names" along with a warning that it "may be slow." This can indeed slow down Chrome DevTools if the component is particularly complex, but it's useful information, especially when you're using multiple hooks in a component. After clicking the wand, you can see that my useState hook is managing a property called hasRead.
What's even cooler is that you can update the values of these hooks directly within the React DevTools, and the state will immediately change in the UI. For example, if I update the hasRead value to true, the corresponding checkbox will instantly reflect that change on the screen.
Lastly below the hook section we see the "rendered by" section, this gives information on parent components responsible for rendering the current component selected.
Stay tuned for more articles on debugging and optimizing React!
Article accurate for version 4.0 of React Developer Tools