简体   繁体   中英

How to track React hooks?

Before working on a new React project, I want to be sure that there are (or will be), good developer tools to support it.

One of the things I like with React is the React Developer tool for Google Chrome. It lets me inspect the internal state for each component.

The question: Does the React Developer tool show the hooks state of a React component?

If not, how can I inspect the internal hooks state (Aka effect), outside of the React component?

Short answer is no, React Devtool doesn't exactly show the hooks state of components the way you want it to . You could track the progress of its implementation here .

The long answer is yes, the React Devtool technically does show state for hooks, but not in a user-friendly format that you are used to. The state is being shown in its raw implementation form, which resembles a linked list:

{
  baseState: ...,
  baseUpdate: ...,
  memoizedState: ...,
  next: {
    baseState: ...,
    baseUpdate: ...,
    memoizedState: ...,
    next: ..., // The list goes on
    queue: ...,
  },
  queue: ...
}

For a simple component with two states, the Devtool shows state as an object with baseState field as the first state value of 'Mary' and there's a next field which points to another state object which corresponds to the second state value, and it has the baseState value of 10 .

function App() {
  const [name, setName] = useState('Mary');
  const [age, setAge] = useState(10);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

在此处输入图片说明

Today, the Chrome Developers React toolbar is able to show the state of hooks.

See the attached image:

在此处输入图片说明

You can inspect React.useState with react-debug-hooks and Redux DevTools

inspect preview

  const [state, setState] = React.useState({
    loading: false,
    users: [],
    error: null
  }, 'users')  // you need to set a second parameter 'string' that will be shown on Redux devTools. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM