Use Debug Value 🚧
Overview¶
useDebugValue
is a React Hook that lets you add a label to a custom Hook in React DevTools.
1 |
|
Reference¶
useDebugValue(value, format?)
¶
Call useDebugValue
at the top level of your custom Hook to display a readable debug value:
1 2 3 4 5 6 7 |
|
Parameters¶
value
: The value you want to display in React DevTools. It can have any type.- optional
format
: A formatting function. When the component is inspected, React DevTools will call the formatting function with thevalue
as the argument, and then display the returned formatted value (which may have any type). If you don't specify the formatting function, the originalvalue
itself will be displayed.
Returns¶
useDebugValue
does not return anything.
Usage¶
Adding a label to a custom Hook¶
Call useDebugValue
at the top level of your custom Hook to display a readable
1 2 3 4 5 6 7 |
|
This gives components calling useOnlineStatus
a label like OnlineStatus: "Online"
when you inspect them:
Without the useDebugValue
call, only the underlying data (in this example, true
) would be displayed.
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Don't add debug values to every custom Hook. It's most valuable for custom Hooks that are part of shared libraries and that have a complex internal data structure that's difficult to inspect.
Deferring formatting of a debug value¶
You can also pass a formatting function as the second argument to useDebugValue
:
1 |
|
Your formatting function will receive the
This lets you avoid running potentially expensive formatting logic unless the component is actually inspected. For example, if date
is a Date value, this avoids calling toDateString()
on it for every render.