JAVASCRIPT
Enhancing Custom Hook Debugging with useDebugValue
Improve the visibility and inspection of your custom React hooks in React DevTools by using the useDebugValue hook to display custom labels.
import React, { useState, useDebugValue } from 'react';
// Custom hook to track online/offline status
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
// Display a custom label in React DevTools
// The second argument is an optional formatter function
useDebugValue(isOnline ? 'Online' : 'Offline');
// Effect to update status (simplified for snippet)
// In a real app, you'd add event listeners for 'online' and 'offline'
// useEffect(() => { ... }, []);
return isOnline;
}
function NetworkStatusIndicator() {
const online = useOnlineStatus();
return (
<div>
<p>Network Status: {online ? '🟢 Online' : '🔴 Offline'}</p>
<p>
Check your React DevTools component tab for "NetworkStatusIndicator"
to see the custom debug value from 'useOnlineStatus'.
</p>
</div>
);
}
export default NetworkStatusIndicator;
How it works: `useDebugValue` is a React hook primarily intended for custom hook authors to display a label for their custom hooks in React DevTools. When inspecting a component that uses a custom hook, `useDebugValue` allows you to provide a more descriptive and readable value that will appear next to the hook's name, making debugging complex state or logic within custom hooks significantly easier. It accepts an optional second argument, a formatter function, for more dynamic display values.