How to use the React.useDebugValue hook

According to the React docs:

useDebugValue is a React Hook that lets you add a label to a custom Hook in React DevTools.

When do I need useDebugValue?

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.

Conclusion

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.