Skip to Content

How do I debug Reactjs code in Chrome?

How do I debug Reactjs code in Chrome?

Reactjs has become one of the most popular JavaScript libraries for building user interfaces. With its declarative component-based architecture, React allows developers to build complex UIs from small reusable pieces of code called components. However, like any complex JavaScript application, bugs and errors can creep into your React codebase. Finding and fixing these issues quickly is critical for maintaining a good developer experience.

Luckily, Chrome DevTools provides some great features for debugging React applications. The React Developer Tools extension allows you to inspect the React component hierarchy, examine props and state, and trace updates. The standard Developer Tools features like breakpoints, the console, network request inspection, and the element inspector are also invaluable for tracking down React bugs. This article will explore the various tools and techniques available for debugging React apps effectively in Chrome.

Enable React Developer Tools

The React Developer Tools is a Chrome extension created specifically for debugging React applications. It allows you to visualize your React component tree, trace component updates, and inspect a component’s current props and state. Installing this extension should be the first step when debugging any React project in Chrome.

To install React Developer Tools in Chrome:

  1. Open the Chrome Web Store and search for “React Developer Tools”
  2. Click “Add to Chrome” to install the extension
  3. A new “React” tab will appear in your Chrome Developer Tools window when you inspect an app using React

Once installed, you can open your React application and open the Chrome Developer Tools (via Command+Option+I on Mac or Control+Shift+I on Windows). Select the new “React” tab in the DevTools window to start debugging your React components.

Inspect the Component Hierarchy

The React Developer Tools let you visually traverse your React component tree. The component hierarchy is displayed in an expandable tree view on the left side of the React tab. You can click on any component to inspect it further in the detailed view on the right side.

Viewing the component structure in this tree allows you to:

  • See the nesting and arrangement of parent/child components
  • Find where a component is rendered in the hierarchy
  • Identify unused components

Often visualizing your component tree can reveal issues like deep or complex component nesting that should be refactored. You may also spot components that are rendered but no longer needed, indicating dead code that should be cleaned up.

Inspect Component Props and State

Once you’ve selected a component in the tree, the React tab will display its props and state values in the panel on the right. You can expand the props and state objects to drill into their data.

Some ways this can help debug React components:

  • Confirm a component is receiving the expected props from its parent
  • See if a component has maintained internal state when it should not
  • Check that props/state has the correct values after an update

You can even edit props/state values directly in the DevTools to test behavior immediately. Note that any local modifications made will reset when you refresh the page.

Trace Component Updates

The React Developer Tools let you profile renders and trace which components are re-rendering over time.

To record renders:

  1. Click the “Profiler” tab in the React Developer Tools
  2. Click the record button (circle icon) to start logging renders
  3. Interact with your application as desired to trigger renders
  4. Click the stop button (square icon) to end recording

This will visually display each component that rendered during the profiling session. You can see the render duration and timing across the whole component tree.

The profiler is invaluable for diagnosing performance issues. You can quickly identify components that are rendering too frequently or have long render times. This helps pinpoint the source of slow, inefficient, or unnecessary renders that should be optimized.

Use Breakpoints

Chrome Developer Tools provides breakpoints for pausing execution and stepping through your JavaScript code. This allows you to debug the flow of your React application line by line.

To add breakpoints:

  1. Open the “Sources” tab in Chrome DevTools
  2. Find and expand the source file you want to debug
  3. Click on the line number where you want to pause execution
  4. A blue breakpoint icon will appear next to the line

Now when you interact with your React app, code execution will pause when a breakpoint is hit. The DevTools window will display the current call stack and scopes. You can step through code line by line while watching values change in real time.

Here are some helpful tips for using breakpoints with React:

  • Look for lifecycle methods like componentDidUpdate to debug rendering issues
  • Pause code execution on AJAX requests to inspect results
  • Set breakpoints within DOM event handlers like onClick to debug interaction code

Breakpoints are also useful when debugging external library code. You can pause execution to understand what’s happening behind the scenes in React, Redux, etc.

Conditional Breakpoints

For additional flexibility, you can set conditional breakpoints that only pause execution when certain criteria are met.

Right click a breakpoint in the DevTools and select “Edit breakpoint”. Here you can enter a conditional expression to control breakpoint behavior.

Some examples of conditional breakpoints:

  • x === 10 (only pause when x is 10)
  • error (only pause on an error)
  • clicks > 10 (only pause after 10 clicks)

Conditionals let you precisely control where code execution pauses. This minimizes debugging steps for faster issue resolution.

Console Logging

Good old console logging can still be highly effective for debugging React apps. Using console statements lets you quickly output variable values at key points in your code.

For example, you could log props, state, or variables before and after a component update:

“`js
// Before update
console.log(‘Count:’, this.state.count);

// Update count
this.setState({count: this.state.count + 1})

// After update
console.log(‘Count:’, this.state.count);
“`

The Console tab in Chrome DevTools neatly organizes console statements from your app. You can even filter the console output by regex patterns and log levels.

Make sure to remove any extraneous console logs when you’re done debugging!

Console Grouping

When logging multiple related values, use console.group() and console.groupEnd() to group the output.

“`js
console.group(‘Before update’)
console.log(‘Count:’, this.state.count);
console.log(‘Name:’, this.state.name);
console.groupEnd();

// Update count & name

console.group(‘After update’)
console.log(‘Count:’, this.state.count);
console.log(‘Name:’, this.state.name);
console.groupEnd();
“`

This groups the two log statements together in the Console output, letting you easily distinguish between before and after values.

Formatting Console Output

To debug complex objects and arrays more easily, use console.table()

“`js
const data = [{
name: ‘John’,
age: 30
}, {
name: ‘Susan’,
age: 32
}];

console.table(data);
“`

This will output the object data in a readable table format in the console.

You can also format console output using styling like console.log(‘%c This text is huge!’, ‘font-size: 20px’)

Network Inspection

Issues making AJAX requests are common in React apps. The Network tab in Chrome DevTools allows inspection of all network requests made from your page.

In the Network panel you can:

  • See all requests with status codes
  • Filter requests by url/type
  • View request and response headers
  • Inspect response body data

This helps debug failed API calls or unexpected response payloads. Network inspection should be one of your first debugging steps for React AJAX issues.

Throttling

The Network tab also lets you throttle your connection speed to simulate slow network environments. This is useful for assessing loading behavior in poor connectivity conditions.

To throttle connections:

  1. Open the Network tab
  2. Open Throttling settings
  3. Select preset throttling values like “Fast 3G”

Now interact with your React app over a throttled connection. Look for issues with loading feedback, content prioritization, and more.

Element Inspection

Inspecting the rendered DOM elements is useful for visual React bugs. Follow these steps:

  1. Open your app in Chrome
  2. Right click on the element you want to inspect
  3. Select “Inspect” to open the Elements panel in DevTools

The Elements panel shows the DOM tree, HTML, styles, and accessibility info. You can use this to:

  • Confirm elements are rendered as expected
  • Visually debug CSS issues like layout, sizing, etc.
  • Inspect component data attributes

Clicking on elements in the DOM tree also highlights them on the page itself. This helps locate misaligned or incorrectly sized elements.

Editing DOM Elements

You can even edit elements directly in the Elements panel to test fixes:

  1. Double click on an element value like text/CSS
  2. Make your changes
  3. Press Enter to commit changes

This provides a quick way to visually test UI fixes before applying them to components.

React-specific Fixes

Certain types of issues are common in React code. Here are some React-specific things to try when debugging:

Check Component Key Assignments

React uses keys to match component instances between renders. Issues like duplicate components or lost state can occur if keys are missing or mismatched.

Verify that unique keys are properly assigned when rendering component arrays.

“`jsx
// A key must be provided to map components to data
{users.map(user =>

)}
“`

Look For Unnecessary Renders

React can re-render components unexpectedly leading to poor performance. The following may cause unnecessary re-renders:

  • Props/state updated even though values did not change
  • Parent components passing new object/array references unnecessarily
  • Using inline functions instead of class methods

Use React.memo on class components or React.useMemo/useCallback hooks to prevent unnecessary renders.

Ensure Data Flows Downstream

Data in React flows from parent to child via props. Avoid passing callbacks down causing data to flow back upstream. This leads to complex, hard to trace data flow.

Instead, pass data down and pass callbacks up via effects and context if needed.

Debugging External Libraries

React apps often use popular libraries like React Router, Redux, and React Query. Chrome Developer Tools provides ways to debug into these libraries to trace code execution.

React Router

Debugging React Router helps trace routing and navigation behavior. Useful techniques include:

  • Logging route changes in componentWillUnmount
  • Inspecting Router component props like history, location, match
  • Adding breakpoints within react-router-dom source code

This helps track down issues like incorrect URL patterns, failed redirects, missing route matches, etc.

Redux

For debugging Redux apps, common techniques are:

  • Logging action types and payloads
  • Inspecting updated Redux state values
  • Tracing action and reducer execution with breakpoints

This helps locate where store state may be incorrectly updated. React Redux hooks like useSelector can also be logged for debugging.

React Query

Debugging React Query involves:

  • Checking request status and error flags in React Query hooks
  • Inspecting cache timing configurations
  • Logging query keys and request URLs

This can reveal issues with data staleness, failed data fetching, or incorrect query setup.

Debugging Production Builds

Debugging React applications is more challenging when issues only occur in production. Here are tips for debugging React apps after they are deployed:

  • Enable source maps so original source code is readable
  • Add logging and telemetry to track errors and behavior
  • Replicate issues locally by serving locally with a production build
  • Use the React Developer Tools browser extensions

Source maps and extensive logging are key for tracing bugs that only happen in production environments and application states.

Conclusion

Debugging React applications effectively requires utilizing all the tools available in Chrome Developer Tools. The React Developer Tools component inspector is indispensable for tracing UI issues. Breakpoints, the Console, Network inspection, and Element inspection help examine application logic and behavior.

Learning debugging best practices like using console formatting, conditional breakpoints, and throttling connections will improve your productivity tracking down React bugs. Optimizing components to avoid unnecessary renders and ensuring proper data flow will also help prevent many common issues.

Mastering React debugging skills using Chrome’s capabilities will help you resolve problems faster and build robust applications.