Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
Aminadav Glickshtein Avatar asked Nov 19 '18 16:11

Aminadav Glickshtein


People also ask

Where do React Hooks go?

Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Is useRef React hook?

useRef(initialValue) is a built-in React hook that accepts one argument as the initial value and returns a reference (aka ref). A reference is an object having a special property current .

How do I find my React Hooks ID?

In React Hooks, You should use useParams() . ex - This is your url - http://localhost:8000/personal/1 . now, if you do console. log(id) , it will give you the exact id of the url.


2 Answers

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>
  );
}

enter image description here

like image 140
Yangshun Tay Avatar answered Oct 26 '22 01:10

Yangshun Tay


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

See the attached image:

enter image description here

like image 38
Aminadav Glickshtein Avatar answered Oct 26 '22 00:10

Aminadav Glickshtein