Blog>
Snippets

React DevTools Extension Updates

Illustrate the new features in React DevTools, including enhancements for debugging and inspecting hooks.

import { useState } from 'react';

function MyComponent() {
  // Using the useState hook which can be inspected with React DevTools
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
This is a React component which uses the useState hook. The state and the corresponding set function are used to keep track of the number of times a button is clicked. React DevTools allow us to inspect the current state and simulate state changes.

import { useEffect } from 'react';

function EffectExample() {
  useEffect(() => {
    // This effect uses the DevTools to show when it's called and with which dependencies
    console.log('Effect has been run');

    return () => console.log('Effect cleanup');
  }); // This effect has no dependencies, runs after every render

  return <div>Check the console for effect logs</div>;
}
Here a React component is utilizing the useEffect hook without any dependencies, meaning it will run after every render. React DevTools can be used to see when this effect is invoked and when it's cleaned up.

import React, { useContext } from 'react';
const MyContext = React.createContext();

function ContextConsumerComponent() {
  const contextValue = useContext(MyContext);
  // React DevTools can now inspect context values

  return <div>The context value is: {contextValue}</div>;
}
This code snippet shows a component that consumes a React context using the useContext hook. React DevTools has the capability to show the current context value which this component consumes.

/* Sample CSS for visualizing the component enhanced by DevTools */
.my-component {
  border: 1px solid #ddd;
  padding: 10px;
  margin: 10px;
}

/* Highlighted when selected in React DevTools */
.my-component.react-devtools-highlight {
  border-color: #5b9dd9;
  background-color: #d6ecf3;
}
This CSS code styles a component and includes a special rule for when the component is highlighted by React DevTools. DevTools can add a special class to indicate which element is being inspected, which, for instance, could change the border and background color to show it's selected.