React devtools chrome

React devtools chrome DEFAULT

Debugging

Accessing the In-App Developer Menu#

You can access the developer menu by shaking your device or by selecting "Shake Gesture" inside the Hardware menu in the iOS Simulator. You can also use the keyboard shortcut when your app is running in the iOS Simulator, or when running in an Android emulator on Mac OS and on Windows and Linux. Alternatively for Android, you can run the command to open the dev menu (82 being the Menu key code).

The Developer Menu is disabled in release (production) builds.

Enabling Fast Refresh#

Fast Refresh is a React Native feature that allows you to get near-instant feedback for changes in your React components. While debugging, it can help to have Fast Refresh enabled. Fast Refresh is enabled by default, and you can toggle "Enable Fast Refresh" in the React Native developer menu. When enabled, most of your edits should be visible within a second or two.

Enabling Keyboard Shortcuts#

React Native supports a few keyboard shortcuts in the iOS Simulator. They are described below. To enable them, open the Hardware menu, select Keyboard, and make sure that "Connect Hardware Keyboard" is checked.

LogBox#

Errors and warnings in development builds are displayed in LogBox inside your app.

LogBox is automatically disabled in release (production) builds.

Console Errors and Warnings#

Console errors and warnings are displayed as on-screen notifications with a red or yellow badge, and the number of errors or warning in the console respectively. To view a console error or warnings, tap the notification to view the full screen information about the log and to paginate through all of the logs in the console.

These notifications can be hidden using . This is useful when giving product demos, for example. Additionally, notifications can be hidden on a per-log basis via . This is useful when there's a noisy warning that cannot be fixed, like those in a third-party dependency.

Ignore logs as a last resort and create a task to fix any logs that are ignored.

Unhandled Errors#

Unhandled JavaScript errors such as will automatically open a full screen LogBox error with the source of the error. These errors are dismissable and minimizable so that you can see the state of your app when these errors occur, but should always be addressed.

Syntax Errors#

When syntax error occurs the full screen LogBox error will automatically open with the stack trace and location of the syntax error. This error is not dismissable because it represents invalid JavaScript execution that must be fixed before continuing with your app. To dismiss these errors, fix the syntax error and either save to automatically dismiss (with Fast Refresh enabled) or cmd+r to reload (with Fast Refresh disabled).

Chrome Developer Tools#

To debug the JavaScript code in Chrome, select "Debug JS Remotely" from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.

Select from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts ( on macOS, on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.

Note: on Android, if the times between the debugger and device have drifted; things such as animation, event behavior, etc., might not work properly or the results may not be accurate. Please correct this by running on your debugger machine. Root access is required for the use in real device.

Note: the React Developer Tools Chrome extension does not work with React Native, but you can use its standalone version instead. Read this section to learn how.

Debugging using a custom JavaScript debugger#

To use a custom JavaScript debugger in place of Chrome Developer Tools, set the environment variable to a command that will start your custom debugger. You can then select "Debug JS Remotely" from the Developer Menu to start debugging.

The debugger will receive a list of all project roots, separated by a space. For example, if you set , then the command will be used to start your debugger.

Custom debugger commands executed this way should be short-lived processes, and they shouldn't produce more than 200 kilobytes of output.

Safari Developer Tools#

You can use Safari to debug the iOS version of your app without having to enable "Debug JS Remotely".

  • Enable Develop menu in Safari:
  • Select your app's JSContext:
  • Safari's Web Inspector should open which has a Console and a Debugger

While sourcemaps may not be enabled by default, you can follow this guide or video to enable them and set break points at the right places in the source code.

However, every time the app is reloaded (using live reload, or by manually reloading), a new JSContext is created. Choosing "Automatically Show Web Inspectors for JSContexts" saves you from having to select the latest JSContext manually.

React Developer Tools#

You can use the standalone version of React Developer Tools to debug the React component hierarchy. To use it, install the package globally:

Note: Version 4 of requires version 0.62 or higher to work properly.

Now run from the terminal to launch the standalone DevTools app:

React DevTools

It should connect to your simulator within a few seconds.

Note: if you prefer to avoid global installations, you can add as a project dependency. Add the package to your project using , then add to the section in your , and then run from your project folder to open the DevTools.

Integration with React Native Inspector#

Open the in-app developer menu and choose "Toggle Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:

React Native Inspector

However, when is running, Inspector will enter a collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:

React DevTools Inspector Integration

You can choose "Toggle Inspector" in the same menu to exit this mode.

Inspecting Component Instances#

When debugging JavaScript in Chrome, you can inspect the props and state of the React components in the browser console.

First, follow the instructions for debugging in Chrome to open the Chrome console.

Make sure that the dropdown in the top left corner of the Chrome console says . This step is essential.

Then select a React component in React DevTools. There is a search box at the top that helps you find one by name. As soon as you select it, it will be available as in the Chrome console, letting you inspect its props, state, and instance properties.

React DevTools Chrome Console Integration

Performance Monitor#

You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu.


Debugging Application State#

Reactotron is an open-source desktop app that allows you to inspect Redux or MobX-State-Tree application state as well as view custom logs, run custom commands such as resetting state, store and restore state snapshots, and other helpful debugging features for React Native apps.

You can view installation instructions in the README. If you're using Expo, here is an article detailing how to install on Expo.

Projects with Native Code Only

The following section only applies to projects with native code exposed. If you are using the managed workflow, see the guide on ejecting to use this API.

Accessing console logs#

You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running:

You may also access these through in the iOS Simulator or by running in a terminal while an Android app is running on a device or emulator.

If you're using Create React Native App or Expo CLI, console logs already appear in the same terminal output as the bundler.

Debugging on a device with Chrome Developer Tools#

If you're using Create React Native App or Expo CLI, this is configured for you already.

On iOS devices, open the file and change "localhost" to the IP address of your computer, then select "Debug JS Remotely" from the Developer Menu.

On Android 5.0+ devices connected via USB, you can use the command line tool to setup port forwarding from the device to your computer:

Alternatively, select "Dev Settings" from the Developer Menu, then update the "Debug server host for device" setting to match the IP address of your computer.

If you run into any issues, it may be possible that one of your Chrome extensions is interacting in unexpected ways with the debugger. Try disabling all of your extensions and re-enabling them one-by-one until you find the problematic extension.

Debugging native code#

When working with native code, such as when writing native modules, you can launch the app from Android Studio or Xcode and take advantage of the native debugging features (setting up breakpoints, etc.) as you would in case of building a standard native app.

Sours: https://reactnative.dev/docs/debugging

New React Developer Tools

A month ago, we posted a beta of the new React developer tools. Today, we’re releasing the first stable version of the new devtools. We’re calling it version 0.14, but it’s a full rewrite so we think of it more like a 2.0 release.

Video/screenshot of new devtools

It contains a handful of new features, including:

  • Built entirely with React, making it easier to develop and extend
  • Firefox support
  • Selected component instance is available as from the console
  • More detail is shown in props in the component tree
  • Right-click any node and choose “Show Source” to jump to the method in the Sources panel
  • Right-click any props or state value to make it available as from the console
  • Full React Native support

Installation

Download the new devtools from the Chrome Web Store, Firefox Add-ons for Firefox, and Microsoft Edge Addons for Edge. If you’re developing using React, we highly recommend installing these devtools.

If you already have the Chrome extension installed, it should autoupdate within the next week. You can also head to and click “Update extensions now” if you’d like to get the new version today. If you installed the devtools beta, please remove it and switch back to the version from the store to make sure you always get the latest updates and bug fixes.

If you run into any issues, please post them on the React GitHub repo.

Is this page useful?Edit this page

Sours: https://reactjs.org/blog/2015/09/02/new-react-developer-tools.html
  1. Yorkies and westies
  2. Kenku monk art
  3. Hamster drinking bottle

npm

React DevTools is available as a built-in extension for Chrome and Firefox browsers. This package enables you to debug a React app elsewhere (e.g. a mobile browser, an embedded webview, Safari, inside an iframe).

It works both with React DOM and React Native.

React DevTools screenshot

Installation

Install the package. Because this is a development tool, a global install is often the most convenient:

# Yarn yarn global add react-devtools # NPM npm install -g react-devtools

If you prefer to avoid global installations, you can add as a project dependency. With Yarn, you can do this by running:

yarn add --dev react-devtools

With NPM you can just use NPX:

Usage with React Native

Run from the terminal to launch the standalone DevTools app:

If you're not in a simulator then you also need to run the following in a command prompt:

adb reverse tcp:8097 tcp:8097

If you're using React Native 0.43 or higher, it should connect to your simulator within a few seconds.

Integration with React Native Inspector

You can open the in-app developer menu and choose "Show Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:

React Native Inspector

However, when is running, Inspector will enter a special collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:

React DevTools Inspector Integration

You can choose "Hide Inspector" in the same menu to exit this mode.

Inspecting Component Instances

When debugging JavaScript in Chrome, you can inspect the props and state of the React components in the browser console.

First, follow the instructions for debugging in Chrome to open the Chrome console.

Make sure that the dropdown in the top left corner of the Chrome console says . This step is essential.

Then select a React component in React DevTools. There is a search box at the top that helps you find one by name. As soon as you select it, it will be available as in the Chrome console, letting you inspect its props, state, and instance properties.

React DevTools Chrome Console Integration

Usage with React DOM

The standalone shell can also be useful with React DOM (e.g. to debug apps in Safari or inside of an iframe).

Run from the terminal to launch the standalone DevTools app:

Add as the very first tag in the of your page when developing:

<!doctype html><htmllang="en"><head><scriptsrc="http://localhost:8097"></script>

This will ensure the developer tools are connected. Don’t forget to remove it before deploying to production!

If you install as a project dependency, you may also replace the suggested above with a JavaScript import (). It is important that this import comes before any other imports in your app (especially before ). Make sure to remove the import before deploying to production, as it carries a large DevTools client with it. If you use Webpack and have control over its configuration, you could alternatively add as the first item in the array of the development-only configuration, and then you wouldn’t need to deal either with tags or statements.

Advanced

By default DevTools listen to port on . If you need to customize host, port, or other settings, see the package instead.

FAQ

The React Tab Doesn't Show Up

If you are running your app from a local URL, don't forget to check "Allow access to file URLs" on the Chrome Extensions settings page. You can find it by opening Settings > Extensions:

Allow access to file URLs

Or you could develop with a local HTTP server like .

The React tab won't show up if the site doesn't use React, or if React can't communicate with the devtools. When the page loads, the devtools sets a global named , then React communicates with that hook during initialization. You can test this on the React website or by inspecting Facebook.

If your app is inside of CodePen, make sure you are registered. Then press Fork (if it's not your pen), and then choose Change View > Debug. The Debug view is inspectable with DevTools because it doesn't use an iframe.

If your app is inside an iframe, a Chrome extension, React Native, or in another unusual environment, try the standalone version instead. Chrome apps are currently not inspectable.

If you still have issues please report them. Don't forget to specify your OS, browser version, extension version, and the exact instructions to reproduce the issue with a screenshot.

Local development

The standalone DevTools app can be built and tested from source following the instructions below.

Prerequisite steps

DevTools depends on local versions of several NPM packages1 also in this workspace. You'll need to either build or download those packages first.

1 Note that at this time, an experimental build is required because DevTools depends on the API.

Build from source

To build dependencies from source, run the following command from the root of the repository:

Download from CI

To use the latest build from CI, run the following command from the root of the repository:

./scripts/release/download-experimental-build.js

Build steps

You can test the standalone DevTools by running the following:

  • First, complete the prerequisite steps above! If you don't do it, none of the steps below will work.
  • Then, run and in
  • Run in this folder
  • Refresh the app after it has recompiled a change
  • For React Native, copy to its to test your changes.
Sours: https://www.npmjs.com/package/react-devtools
How to use the React Profiler to find and fix Performance Problems

React Chrome Developer Tools

With the new year, we thought you’d enjoy some new tools for debugging React code. Today we’re releasing the React Developer Tools, an extension to the Chrome Developer Tools. Download them from the Chrome Web Store.

You will get a new tab titled “React” in your Chrome DevTools. This tab shows you a list of the root React Components that are rendered on the page as well as the subcomponents that each root renders.

Selecting a Component in this tab allows you to view and edit its props and state in the panel on the right. In the breadcrumbs at the bottom, you can inspect the selected Component, the Component that created it, the Component that created that one, and so on.

When you inspect a DOM element using the regular Elements tab, you can switch over to the React tab and the corresponding Component will be automatically selected. The Component will also be automatically selected if you have a breakpoint within its render phase. This allows you to step through the render tree and see how one Component affects another one.

react dev tools

We hope these tools will help your team better understand your component hierarchy and track down bugs. We’re very excited about this initial launch and appreciate any feedback you may have. As always, we also accept pull requests on GitHub.

Is this page useful?Edit this page

Sours: https://reactjs.org/blog/2014/01/02/react-chrome-developer-tools.html

Devtools chrome react

Before you can do that To complete this action, sign in to your Community account or create a new one.

The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

Introduction

Since React apps are made to scale and grow quickly, it’s easy for subtle bugs to infiltrate your code. The React Developer Tools browser extension can help you track down these bugs by giving you more insight into the current state for each component. React Developer Tools gives you an interface for exploring the React component tree along with the current props, state, and context for individual components. React Developer Tools also lets you determine which components are re-rendering and can generate graphs to show how long individual components take to render. You can use this information to track down inefficient code or to optimize data-heavy components.

This tutorial begins by installing the React Developer Tools browser extension. You’ll then build a text analyzer as a test application, which will take a block of text and display information such as word count, character count, and character usage. Finally, you will use React Developer Tools to explore the text analyzer’s components and keep track of the changing props and context. The examples will use the Chrome browser, but you can also use the plugin for Firefox.

By the end of this tutorial, you’ll be able to start using the React Developer Tools to debug and explore any React project.

Prerequisites

  • To use the Chrome React Developer Tools extension, you will need to download and install the Google Chrome web browser or the open-source Chromium web browser. You can also following along using the React Developer Tools FireFox plugin for the FireFox web browser.

  • You will need a development environment running Node.js; this tutorial was tested on Node.js version 10.22.0 and npm version 6.14.6. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

  • A React development environment set up with Create React App. To set this up, follow Step 1 — Creating an Empty Project of the How To Manage State on React Class Components tutorial, which will remove the non-essential boilerplate. This tutorial will use as the project name.

  • You will be using React components and Hooks in this tutorial, including the and context Hooks. You can learn about components and Hooks in our tutorials How To Create Custom Components in React, How To Manage State with Hooks on React Components, and How To Share State Across React Components with Context.

  • You will also need a basic knowledge of JavaScript and HTML, which you can find in our How To Build a Website with HTML series and in How To Code in JavaScript. Basic knowledge of CSS would also be useful, which you can find at the Mozilla Developer Network.

Step 1 — Installing the React Developer Tools Extension

In this step, you’ll install the React Developer Tools broswer extension in Chrome. You’ll use the developer tools in the Chrome JavaScript console to explore the component tree of the project you made in the Prerequisites. This step will use Chrome, but the steps will be nearly identical for installing the React Developer Tools as an add-on in Firefox.

By the end of this step, you’ll have the React Developer Tools installed in your browser and you’ll be able to explore and filter components by name.

The React Developer Tools is a plugin for the Chrome and Firefox browser. When you add the extension, you are adding additional tools to the developer console. Visit the Chrome plugin page for React Developer Tools to install the extension.

Click on the Add to Chrome button. Then click on the Add extension button to confirm:

Chrome add extension button

Chrome will install the extension, and a success message and a new icon will appear in the upper right corner of your browser next to the address bar:

Chrome success message

If the icon does not appear, you can add it by clicking on the puzzle piece, then clicking on the pushpin icon by the React Developer Tools:

Pin extension

When you are on a page that does not have any React components, the icon will appear gray. However, if you are on a page with React components, the icon will appear blue and green. If you click on the icon, it will indicate that the application is running a production version of React.

Visit , to find that the homepage is running a production version of React:

DigitalOcean React Production Build information

Now that you are on a website that uses React, open the console to access the React Developer Tools. Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console.

When you open the console, you’ll find two new tabs: Components and Profiler:

Console Open

The Components tab will show the current React component tree, along with any props, state, or context. The Profiler tab lets you record interactions and measure component rendering. You’ll explore the Profiler tab in Step 3.

Click on the Components tab to see the current component tree.

Since this is a production build, the code will be minified and the components will not have descriptive names:

Components for digitalocean.com in the console

Now that you’ve tried out React Developer Tools on a working website, you can use it on your test application. If you haven’t started your application yet, go to a terminal window and run from the root of the project.

Open a browser to .

Notice that the icon for React Developer Tools is now red and white. If you click on the React Developer Tools icon, you’ll see a warning that the page is in development mode. Since you are still working on the sample application, this is expected.

Open the console and you’ll find the name of the component in the Components tab.

Base Component

There’s not a lot of information yet, but as you build out the project in the next step, you’ll see all of your components forming a navigable tree.

In this step, you added the React Developer Tools extension to Chrome. You activated the tools on both a production and a development page, and you briefly explored your project in the Components tab. In the next step, you’ll build the text analyzer that you’ll use to try out the features of the React Developer Tools.

Step 2 — Identifying Real-Time Component Props and Context

In this step, you’ll build a small application to analyze a block of text. The app will determine and report the word count, character count, and character frequency of the text in the input field. As you build the application, you’ll use React Developer Tools to explore the current state and props of each component. You’ll also use React Developer Tools to view the current context in deeply nested components. Finally, you’ll use the tools to identify components that re-render as state changes.

By the end of this step, you’ll be able to use the React Developer Tools to explore a live application and to observe the current props and state without console statements or debuggers.

To start, you will create an input component that will take a large amount of text.

Open the file:

Inside the component, add a with a class of , then create a element surrounding a element:

debug-tutorial/src/components/App/App.js

This will be the input area for your user. The attribute links the element to elements with an of using JSX. You also give the component rows and columns to provide room for a large amount of text.

Save and close the file. Next, open :

Add some styling to the application by replacing the contents with the following:

debug-tutorial/src/components/App.App.css

Here you add some padding to the class, then simplify child elements by removing the background color and adding some margin. Finally, you add a small margin to child elements. These styles will apply to components you will build to display information about the text.

Save the file. When you do, the browser will refresh and you’ll see the input:

Text area

Open :

Next, create a context to hold the value from the element. Capture the data using the Hook:

debug-tutorial/src/components/App/App.js

Be sure to export , then wrap the whole component with the . Capture the data by adding an prop to your element.

Save the file. The browser will reload. Be sure that you have React Developer Tools open and notice that component now shows the as a child component.

Component context in React Developer Tools

The component by default has a generic name——but you can change that by adding a property to the generated context. Inside , add a line where you set the to :

debug-tutorial/src/components/App/App.js

It is not necessary to add a , but it does help to navigate components when analyzing the component tree in the console. You will also see the value of the Hook in the side bar. Type some text in the input and you’ll see the updated value in React Developer Tools under the hooks section on the component.

Update Value in Developer Tools

The Hook also has a generic name of , but this is not as easy to update as the context. There is a Hook, but it only works on custom Hooks and is not recommended for all custom Hooks.

In this case, the state for the component is the prop to . Click on the in the React Developer Tools and you’ll see that the also reflects the input value that you set with the state:

Updated value for the context

React Developer Tools is showing you real time prop and context information, and the value will grow as you add components.

Next, add a component called . This component will be a container for the components with specific data analysis, such as the word count.

First, make the directory:

Then open in your text editor.

Inside the component, you will have three separate components: , , and . You’ll make these components in just a moment.

The component will use the Hook to toggle the display of each component. Create a function that toggles the display value of each component and a button to toggle each component with an action:

debug-tutorial/src/components/TextInformation/TextInformation.js

Notice that your Hook starts with an object that maps each key to a boolean. The reducer function uses the spread operator to preserve the previous value while setting a new value using the parameter.

Save and close the file. Then open :

Add in your new component:

debug-tutorial/src/components/App/App.js

Save and close the file. When you do, the browser will reload, and you’ll see the updated component. If you click on in React Developer Tools, you’ll see the value update on each button click:

Update Reducer on Click

Now that you have the container component, you’ll need to create each informational component. Each component will take a prop called . If is falsy, the component will return . The components will consume the , analyze the data, and display the result.

To start, create the component.

First, make a new directory:

Then, open in your text editor:

Inside the component, create a function that uses the prop and displays if is falsy:

debug-tutorial/src/components/CharacterCount/CharacterCount.js

Inside the function, you assign the value of to a variable using the Hook. You then return a that shows the character count using the method. Finally, adds a weak typing system to provide some enforcement to make sure the wrong prop type is not passed.

Save and close the file. Open :

Import and add the component after the buttons, passing as the prop:

debug-tutorial/src/components/TextInformation/TextInformation.js

Save the file. The browser will reload and you’ll see the component in the React Developer Tools. Notice that as you add words in the input, the context will update. If you toggle the component, you’ll see the props update after each click:

Adding text and toggling

You can also manually add or change a prop by clicking on the property and updating the value:

Manually Changing Props

Next, add a component.

Create the directory:

Open the file in a text editor:

Make a component that is similar to , but use the method on spaces to create an array of words before showing the length:

debug-tutorial/src/components/WordCount/WordCount.js

Save and close the file.

Finally, create a component. This component will show how often a specific character is used in a block of text. It will then sort the characters by frequency in the passage and display the results.

First, make the directory:

Next, open in a text editor:

Import and use the component and use the prop to display results as you did in the previous components:

debug-tutorial/src/components/CharacterMap/CharacterMap.js

This component will need a slightly more complicated function to create the frequency map for each letter. You’ll need to go through each character and increment a value anytime there is a repeat. Then you’ll need to take that data and sort it so that the most frequent letters are at the top of the list.

To do this, add the following highlighted code:

debug-tutorial/src/components/CharacterMap/CharacterMap.js

In this code, you create a function called that splits the text into an array of characters using the string method. Then you the array to an object by adding the character and then incrementing the count for each subsequent character. Finally, you convert the object to an array of pairs using and to put the most used characters at the top.

After you create the function, you pass the text to the function in the method and over the results to display the character—array value —and the count—array value —inside a .

Save and close the file. This function will give you an opportunity to explore some performance features of the React Developer Tools in the next section.

Next, add the new components to and look at the values in React Developer Tools.

Open :

Import and render the new components:

debug-tutorial/src/components/TextInformation/TextInformation.js

Save and close the file. When you do, the browser will refresh, and if you add in some data, you’ll find the character frequency analysis in the new components:

CharacterMap Component in React Developer Tools

In this section, you used React Developer Tools to explore the component tree. You also learned how to see the real-time props for each component and how to manually change the props using the developer tools. Finally, you viewed the context for the component change with input.

In the next section, you’ll use the React Developer Tools Profiler tab to identify components that have long render times.

Step 3 — Tracking Component Rendering Across Interactions

In this step, you’ll use the React Developer Tools profiler to track component rendering and re-rendering as you use the sample application. You’ll navigate flamegraphs, or visualizations of your app’s relevant optimization metrics, and use the information to identify inefficient components, reduce rendering time, and increase application speed.

By the end of this step, you’ll know how to identify components that render during user interactions and how to compose components to reduce inefficient rendering.

A quick way to see how components change each other is to enable highlighting when a component is re-rendered. This will give you a visual overview of how the components respond to changing data.

In React Developer Tools, click on the Settings icon. It will look like a gear:

Settings icon

Then select the option under General that says Highlight updates when components render.

Highlight changes

When you make any changes, React Developer Tools will highlight components that re-render. For example, when you change input, every component re-renders because the data is stored on a Hook at the root level and every change will re-render the whole component tree.

Notice the highlighting around the components, including the top of the screen around the root component:

Highlighting Text

Compare that to how the components re-render when you click on one of the buttons to toggle the data. If you click one of the buttons, the components under will re-render, but not the root component:

Rerendering lower components only

Showing the re-renders will give you a quick idea of how the components are related, but it doesn’t give you a lot of data to analyze specific components. To gain more insight, let’s look at the profiler tools.

The profiler tools are designed to help you measure precisely how long each component takes to render. This can help you identify components that may be slow or process intense.

Re-open the settings and uncheck the box for Highlight updates when components render. Then click on the Profiler tab in the console.

To use the profiler, click the blue circle on the left of the screen to begin recording and click it again when you are finished:

Start profiling

When you stop recording, you’ll find a graph of the component changes including, how long each item took to render.

To get a good sense of the relative efficiency of the components, paste in the Wikipedia page for Creative Commons. This text is long enough to give interesting results, but not so big that it will crash the application.

After pasting in the text, start the profiler, then make a small change to the input. Stop profiling after the component has finished re-rendering. There will be a long pause, because the application is handling a long re-rendering:

Adding a change with a lot of text

When you end the recording, React Developer Tools will create a flamegraph that shows every component that re-rendered and how long it took to re-render each component.

In this case, every keypress from the word “Change” causes a re-render. More importantly, it shows how long each render takes and why there was a long delay. The components , , and take about .2 milliseconds to rerender. But the component takes around 1 second per keystroke to re-render because of the complicated data parsing in the function.

In the display, each yellow bar is a new keystroke. You can replay the sequence one at a time by clicking on each bar. Notice that there is slight variation in the render times, but the is consistently slow:

Looking at the flamegraph

You can get more information by selecting the option Record why each component rendered while profiling. under the Profiler section of the settings.

Try toggling the Word Count component and notice how long the changes take. The application still lags even though you haven’t changed the text content:

Word Count toggle flamegraph

Now when you hover your cursor over a component, you’ll find that it includes a reason the component re-rendered. In this case, the reason the component changed is The parent component rendered. That’s a problem for the component. is doing an expensive calculation every time the parent changes, even if the props and the context do not change. That is, it’s recalculating data even though the data is identical to the previous render.

Click on the Ranked tab and you’ll find how much more time takes when compared to all other components:

Ranked Tab

React Developer Tools have helped isolate a problem: the component re-renders and performs an expensive calculation anytime any parent component changes.

There are multiple ways to solve the problem, but they all involve some sort of caching via memoization, a process by which already calculated data is remembered rather than recalculated. You can either use a library like lodash/memoize or memoize-one to cache the results of the function, or you can use the built in React function to memoize the whole component.

If you use the React , the function will only re-render if the props or context change. In this case, you’ll use React . In general, you should memoize the data itself first since it’s a more isolated case, but there are some interesting changes in the React Developer Tools if you memoize the whole component, so you’ll use that approach in this tutorial.

Open :

Import from React, then pass the entire function into the function:

debug-tutorial/src/components/CharacterMap/CharacterMap.js

You move the line to the end of the code in order to pass the component to right before exporting. After that, React will compare the props before re-rendering.

Save and close the file. The browser will reload, and when you toggle the , the component will update much faster. This time, does not re-render. Instead, in React Developer Tools, you’ll see a gray rectangle showing re-rendering was prevented.

React Developer Tools showing that CharacterMap did not re-render

If you look at the Ranked tab, you’ll find that both the and the re-rendered, but for different reasons. Since is not memoized, it re-rendered because the parent changed. The re-rendered because the props changed. Even if it was wrapped in , it would still rerender.

Ranked view of memoized app

Note: Memoizing is helpful, but you should only use it when you have a clear performance problem, as you did in this case. Otherwise, it can create a performance problem: React will have to check props every time it re-renders, which can cause a delay on smaller components.

In this step, you used the profiler to identify re-renders and componenent re-rendering. You also used flamegraphs and ranked graphs to identify components that are slow to re-render and then used the function to prevent re-rendering when there are no changes to the props or context.

Conclusion

The React Developer Tools browser extension gives you a powerful set of utilities to explore your components in their applications. With these tools, you’ll be able to explore a component’s state and identify bugs using real data without console statements or debuggers. You can also use the profiler to explore how components interact with each other, allowing you to identify and optimize components that have slow rendering in your full application. These tools are a crucial part of the development process and give you an opportunity to explore the components as part of an application and not just as static code.

If you would like to learn more about debugging JavaScript, see our article on How To Debug Node.js with the Built-In Debugger and Chrome DevTools. For more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.

Sours: https://www.digitalocean.com/community/tutorials/how-to-debug-react-components-using-react-developer-tools
React Developer Tools - Components \u0026 Profiler

Debug React applications with React DevTools

Editor’s Note: This article was revised in January 2021 to reflect recent updates to React DevTools. 

Why should you debug React applications?

Debugging is one of the most useful skills a developer can possess. It allows you to properly navigate and spot errors in your code quickly and efficiently. In the modern web, this is made possible by leveraging various tools and techniques.

React is one of the fastest-growing front-end frameworks. It makes creating complex and interactive UIs painless. Like other frameworks, it has a debugging toolset called React development tools.

What is React DevTools?

React development tools (React DevTools) is a browser extension available for Chrome, Firefox, and as a standalone app that allows you to inspect the React component hierarchy in the Chrome developer tools. It provides an extra set of React-specific inspection widgets to assist you with development. Since its inception, there have been many releases from the core team.

In this tutorial, I’ll highlight the notable additions to the latest React DevTools release and demonstrate a few ways you can leverage its features to better debug your React apps with it.

How to install React DevTools

React DevTools is available as an extension for Chrome and Firefox. If you have already installed the extension, it should update automatically. If you use the standalone shell (e.g. in React Native or Safari), you can install the new version from NPM:

npm install -g [email protected]^4

Setting up our test application

I created a starter project for easy setup and to reduce overhead, ensuring the article focuses on debugging. The skeleton of the application has already been set up, it includes a few components, styling and project structure. Run the following command to clone the repository if you want to experiment with me:

git clone https://github.com/Kennypee/react-contacts

Open the folder and install the project’s dependencies by running the following command:

cd react-contacts && npm install

To start the React app server, run the command in the root folder of your project. Open your browser to and you will see the project live!

test application debug react devtools

React DevTools Performance improvements

DevTools offers significant performance gains and improved navigation experience. Certain aspects have been modified to make it usable for larger applications.

Filtering components with React DevTools

In previous versions of DevTools, navigating through large component trees has been a little bit tedious. But now, DevTools provides a way to filter components so that you can hide ones you’re not interested in.

To access this feature, let’s filter through the three components in our sample application. Open your DevTools and you will see our three components listed.

React devtools debug application filter components

To filter out a component and focus on the one we are interested in, click on the setting icon below the components tab. You’ll be presented with a popup. Click on the components tab and choose your preferred sorting option.

react devtools debug filter components

After we filter out components, they become hidden by default but will become visible after disabling the filter. This feature will come in handy when you work on a project with many components and fast sorting becomes a real need. What’s even more interesting about this feature is that filter preferences are remembered between sessions.

Inline props in React DevTools are now a thing of the past

To make larger component trees easier to browse and to make DevTools faster, components in the tree no longer show inline props.

To see this feature in action, all you need to do is select a component and all the components’ props, state, and Hooks will be displayed on the right-hand side of the console.

In our sample application, we only pass props to our component. Clicking on it will reveal the value of the props passed to it and clicking on the other components will reveal that no props were passed to them.

React devtools debug list of components

Although this feature may not be so useful for smaller React projects, it will come in handy when working with large React projects.

Debugging unexpected prop values and component elements

Consider the following React class:

import ABC from 'abc'; import XYZ from 'xyz'; class Main extends Component { constructor(props) { super(props); this.state = { name : "John" } } render() { const { name } = this.state; return ( <ABC> <XYZ name={name} /> </ABC> ) } }

is the parent of but is the owner of the component and only owners can send down props.

In the newer version of React Dev tools, you can quickly debug an unexpected prop value by skipping over the parents. DevTools v4 adds a list in the right-hand pane that allows you to quickly step through the list of owners to speed up your debugging process.

By clicking on any of the components in our application, we can see the components that rendered them. This is very useful when trying to trace back the origin of a particular prop.

React devtools debug component list

It also comes with an inverse function called . It is the list of things rendered by a particular component — the things it “owns”. This view is kind of like looking at the source of the component’s render method and can be a helpful way to explore large, unfamiliar React applications.

To use this feature to debug our application, double click a component to view the owners’ tree and click the “x” button to return to the full component tree. You can also move around in the tree to see all the children of the component.

react devtools debug contact component 2

Visual improvements in React DevTools

Indented component view

In the previous versions of React DevTools, deeply nested components require both vertical and horizontal scrolling to see, which makes tracking large component trees difficult. DevTools now dynamically adjust nesting indentation to eliminate horizontal scrolling.

To use this feature in our app, click on the components tab, then click on any component and all its children will automatically appear below it with an automatic indentation from the next component.

React devtools debug child component

Improved searching

Previously, when searching in DevTools, the result is often a filtered components tree showing matching nodes as roots, i.e., other components are hidden and the search match now display as root elements. This made the overall structure of the application harder to reason about because it displayed ancestors as siblings.

Now, you can easily search through your components with results shown inline similar to the browser’s find-in-page search.

react devtools debug inline search

Functional improvements in React DevTools

Improved Hooks support

Hook-based React projects can be debugged faster and better because Hooks in version 4 now have the same level of support as props and state. Values can be edited, arrays and objects can be drilled into, etc.

react devtools debug hooks

Restoring selection between reloads

While debugging, if you hit reload, DevTools now attempts to restore the last selected element.

Let’s assume we were sorting through the component in our sample application before a page refresh occurs, DevTools will resume with the component automatically selected.

react devtools debug restore selection

Suspense toggle

React’s Suspense API lets components “wait” or do “something” before rendering. components can be used to specify loading states when components deeper in the tree are waiting to render.

DevTools lets you test these loading states with this toggle:

react devtools debug suspense

Profiler changes in React DevTools

Reload and profile

The profiler is a powerful tool for performance tuning React components. Legacy DevTools supported profiling but only after it detected a profiling-capable version of React. Because of this, there was no way to profile the initial mount (one of the most performance-sensitive parts) of an application.

This feature is now supported with a “reload and profile” action:

Component renders list

The profiler displays a list of each time the selected component rendered during a profiling session, along with the duration of each render. This list can be used to quickly jump between commits when analyzing the performance of specific components.

For our sample application, we can see that some components render twice during the section, we now have a direction toward debugging that may potentially improve performance.

Support for React DevTools

Only the following versions of React are supported:

react-dom
0-14.x: Not supported
15.x: Supported (except for the new component filters feature)
16.x: Supported

react-native
0-0.61: Not supported
0.62: Supported
0.63: Supported

So if certain features don’t work on a particular project, be sure to check the version of React you are using.

LogRocket: The ultimate React debugging solution

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket. LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — start monitoring for free.

Conclusion

In this tutorial, we have talked about debugging React applications with DevTools. We looked at some additions and improvements that came with it. We also looked at how they make debugging your code easier. If you have any questions, comments, or additions be sure to drop a comment. Happy coding!

Sours: https://blog.logrocket.com/debug-react-applications-with-the-new-react-devtools/

Similar news:

Introducing the New React DevTools

We are excited to announce a new release of the React Developer Tools, available today in Chrome, Firefox, and (Chromium) Edge!

What’s changed?

A lot has changed in version 4! At a high level, this new version should offer significant performance gains and an improved navigation experience. It also offers full support for React Hooks, including inspecting nested objects.

DevTools version 4 screenshot

Visit the interactive tutorial to try out the new version or see the changelog for demo videos and more details.

Which versions of React are supported?

  • -: Not supported
  • : Supported (except for the new component filters feature)
  • : Supported

  • -: Not supported
  • : Supported

How do I get the new DevTools?

React DevTools is available as an extension for Chrome and Firefox. If you have already installed the extension, it should update automatically within the next couple of hours.

If you use the standalone shell (e.g. in React Native or Safari), you can install the new version from NPM:

Where did all of the DOM elements go?

The new DevTools provides a way to filter components from the tree to make it easier to navigate deeply nested hierarchies. Host nodes (e.g. HTML , React Native ) are hidden by default, but this filter can be disabled:

DevTools component filters

How do I get the old version back?

If you are working with React Native version 60 (or older) you can install the previous release of DevTools from NPM:

For older versions of React DOM (v0.14 or earlier) you will need to build the extension from source:

Thank you!

We’d like to thank everyone who tested the early release of DevTools version 4. Your feedback helped improve this initial release significantly.

We still have many exciting features planned and feedback is always welcome! Please feel free to open a GitHub issue or tag @reactjs on Twitter.

Is this page useful?Edit this page

Sours: https://reactjs.org/blog/2019/08/15/new-react-devtools.html


285 286 287 288 289