How to use the React.useDebugValue hook

Backend developer with strong experience in the .NET ecosystem and AWS. Other development skills include JavaScript/React/Vue, HTML, CSS.
Search for a command to run...

Backend developer with strong experience in the .NET ecosystem and AWS. Other development skills include JavaScript/React/Vue, HTML, CSS.
No comments yet. Be the first to comment.
According to the React docs: useRef is a React Hook that lets you reference a value that’s not needed for rendering. Here are two examples where useRef should be used: Referencing a value with a ref Manipulating the DOM with a ref Referencing a...

Understand what really happens when you don't pass the key prop when rendering a list in React

Implement AWS Cognito authentication using Authorization Code Grant with hosted UI into your Nextjs application

Start writing your own Cypress tests in React

According to the React docs:
useDebugValueis a React Hook that lets you add a label to a custom Hook in React DevTools.
useDebugValue becomes important when you implement a custom hook.
For example, let's say you have a component called Counter. It manages a count state and allows you to increment and decrement that value.
const useCounter = () => {
const [count, setCount] = React.useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
if (count > 0) {
setCount(count - 1);
}
};
return {
count,
increment,
decrement,
};
};
const Counter = () => {
const { count, increment, decrement } = useCounter();
return (
<div>
<h2>Counter App</h2>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
Using React Dev Tools, you can view the current state within the hook. However, you are not provided with much information. The context may be clear in this example because we are only storing a count. But if there were multiple different states, it would be much harder to understand what is going on.

useDebugValue will accept any value. You could simply include a state variable directly, however, it is recommended to display information in a more useful format. For example, I can display whether the count is greater or less than 10.
const [count, setCount] = React.useState(0);
React.useDebugValue(count > 10 ? "Greater than 10" : "Less than 10");
...
Now you view the Components tab, you can see the debug value.Feel

Feel free to play around with the example below.
Hopefully, you will now have a decent understanding of how to use useDebugValue in your React application. It should come in handy when managing complex state within a custom hook.