Thanks to chrome’s debugging capabilities, console.log is the most straightforward way to solve an unknown problem in front-end development. However, there is a better debugging solution in the React project. That is the official React DevTools (Facebook), which can do some specific code debugging. If you want to try react DevTools, check out this article to see what the tool can do. (Long warning, please Mark 👍)

Install & open ⚒

The installation

React DevTools was introduced as a browser plugin in the React Project on the Web. You can add the react DevTools plugin in Chrome and firefox. Go to the menu ->Web Developers -> Get more Tools -> search for “React Developer Tools”- > Install

chrome: firefox:

To open the Chrome Web store, you may need scientific Internet access, while Firefox does not need scientific Internet access to install plug-ins, and use the same

Tool entrance

If the react project is detected, the tool icon in the upper right corner (right side of the address bar) will change to:

Debug version of react project, coding👨🏻💻

A production version of React has been packaged and released

React indicates that the current version of react is older and usually appears in Act15 or earlier versions

There are no react dependencies detected in the Web ❌

React DevTools allows you to use ⚛️ Components and ⚛️ Profiler tabs at the end of the debugger.

JSX structure tree 🌲

To facilitate the demonstration function, here is a commonTable showsandThe search function, the component level isUserThere are two components under the componentUserSearch 和 UserListComponents.

positioning

JSX 是 ReactKey points in grammar,ComponentsThe tools are also a big part of the presentationreact 的 JSXvirtualDomTree, the pick icon in the upper left corner is used withchrome devtoolsThe pick is the same, click to locate the specific component you want to see details.

Locate theUserSearchcomponent

I used some in the projectReact-router , reduxWait for tools after virtualDomTrees can be invaded, for exampleDomA little bit more in the treeConext.ConsumerAnd these arecontextIn spite of these structures,Double click on theThe target component can be drilled into the detailed structure of the component, for example, by double-clickingUserComponents:Isn’t that much clearer,UserUnder aSuspense , SuspenseThere are two custom components, highlighted in red globallyDomAll the levels in the tree.

Suspense is used with the react lazy loading, document: zh-hans.reactjs.org/docs/code-s…

The filter

Another trick is to easily filter out those that do not want to show the Dom. Click on the setting widget, and there is a drop-down bar for component Settings. Then go to “Hide Components Where “and add a filter to filter the Dom. Here is a list of what each configuration represents.

Filter first column key:

The name of the meaning
location Router Indicates the component that matches the route
name Group price
type Breakdown of various component types (refer to table below)
hoc High order component

Location and name are both reged-matched

Type Optional value:

The name of the meaning
class Class component that inherits react.component.component.class
context Shared context Context
function Functional component
forward ref Functional components pass Ref’s HOC
host(e.g

)
Browser supported HTML elements, div, H1, P
memo Functional components do props optimized HOC
other Others ❓ (to be added)
profiler performance-measuring
suspense Lazy loading of the root component

Single component debugging 🔧

After locating the target component, you can perform single-component debugging. Double-click on the component. On the right side of react DevTools, information about the component is displayed, such as props, State, hooks, and Render by.

propsYou can see that,UserComponent isRouterThe first tier of components below will havelocation , history , matchFor additional information.

The root state of the hooks is missing the attribute name. For the time being, useState({MSG: ‘hello’}) can be used to get around this. Hopefully, future iterations will fix this

Light can not be used to see attributes, but only to see and use them. Careful digging has found a row of ICONS in the upper right corner:




1. The lazy fallback status is displayed

In Suspense, the timing button is related to lazy loading. When children in Suspense components are not loaded, there is a loading effect. In Suspense, clicking the button will show the ReactNode in fallback. It’s a good way to preview loading.

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>} ><OtherComponent />
      </Suspense>
    </div>
  );
}
Copy the code

Here, the Skeleton effect of ANTD is introduced as the intermediate state of loading. The small icon highlighted indicates that the state is in loading state.

2. Check the actual Dom of the component

inReactWriting in theJSXNone of the component trees rendered by the code are actually realDOMTrees, so there areDebugging style,Modify the documentDirect operationDOMDemand, or need to cut backchrome devtools 的 ElementAnd then locateElementAnother pick up operation is slightly inconvenient, and the button with the little eye icon is used to locate the component’s real Dom.Here byUserSearchThe component is located to the realdomTrees, for some of the deeper levelsdomStructure, orz-indexThis feature location is quite convenient for dom hierarchies.

3. The debug information

The bug button will be very confusing at the beginning of the use, after clicking it seems to have no effect, then hover for a moment will have a text:

Log this component data to the console

Then switch to the Chrome DevTools console and you’ll see the component information associated with UserSearch:

According to the prompts,Right clickAny value, then click “Store as global variable” and save asThe global variableSo, we’re choosing herePropsUnder theonSearchMethods:

consoleA new one will appear intemp1The variable, the variable is pointingonSearchCall to the reference value oftemp1The function is equivalent toonSearch , onSearchThe business logic is based on parametersfilterUser list, here is the filter to contain “xu” records:

This kind ofdebugMethod is convenient in some special scenarios, such as through ordinary page interaction cannot trigger, needThe asynchronous interfaceThe return value is triggered and so on.

4. Locate source-map information

The last button is very familiar, usually in someComponent library documentationCode examples, such asantd , fusion , iviewAnd other UI component libraries that serve as debug portals for unwrapping code,react devtoolsThe function is similar, here is to locate the corresponding componentSourceFiles, I’m going to switch over hereUserSearchThe correspondingindex.tsxFile, configured in the development environmentsource-map, positioning components can be displayed directlyThe source code.Here,sourceIt’s very powerful, and the most commonly used isBreaking pointFor example, we areresetTriggerThere are two breakpoints in the breakpoint, click reset button will trigger the breakpoint:

The Scope in the right pane contains closure information, which is actually generated by the useState API to save functional components, and filter is the content of the input box. This debugging can avoid the need to recompile the project after console.log changes the code. You might also leave some dirty code behind.

Performance problem tracking 🚥

The React profiler API can be added anywhere in the React tree to measure the overhead incurred by rendering parts of the tree. The profiler API can be added anywhere in the tree to measure the overhead incurred by rendering parts of the tree.

render(
  <App>
    <Profiler id="Navigation" onRender={callback}>
      <Navigation {. props} / >
    </Profiler>
    <Main {. props} / >
  </App>
);
Copy the code

The input parameter of the onRender callback contains all the rendering information of the subcomponent, which is helpful for checking the performance of the component:

function onRenderCallback(
  id, // The "ID" of the Profiler tree in which the commit occurred
  phase, // one of "mount" (if the component tree was just loaded) or "update" (if it was rerendered)
  actualDuration, // Committed The committed rendering time
  baseDuration, // Estimate the time required to render the entire subtree without memoization
  startTime, // React starts rendering time in this update
  commitTime, React COMMITTED time in this update
  interactions // This is the set of interactions
) {
  // Add up or record render times...
}
Copy the code

The official document links: zh-hans.reactjs.org/docs/profil…

Although debugging in a project is flexible, it can cause code intrusion and even performance degradation. Therefore, when using a global profiler, you can first try using the Profiler function of React DevTools.

Now to test this outprofilerFunction,UserListTen thousand records have been added to the component to show how much time it takes:Here is a typical performance analysisFlame figure, shows the time consumption of each component in the current page. If there is an abnormal component that consumes a long time, the horizontal bar chart will display asyellowAnd even more alarming 🚨 colors, which are obvious here,UserList“Took quite a long time, which was in line with our expectations.

inprofilerSystem Settings, can also turn on components when to render switches, as wellhiddenFixed render time for the following components:

Why did this renderRouteThe component was rendered for the first time, rendering for 12.8 milliseconds

End ⌛ ️

React Devtools provides you with a tutorial on how to debug react Devtools. You can use 👇 to learn how to debug react Devtools.

portal

PS: If there are any mistakes in this article, please kindly correct them

Past wonderful 📌

  • Vue3 hugs TypeScript properly ✨
  • Vue3-one piece尝鲜:React Hooks VS Composition API ✨
  • Optimize performance ✨