What is useDebugValue?
useDebugValue is a specialized hook designed purely for improving the developer experience. It allows you to display custom, readable labels for your custom hooks inside the React Developer Tools extension.
Why it exists:
When you build complex custom hooks (e.g., useAuth, useMediaQuery), React DevTools just shows a nested list of the internal hooks (like useState and useEffect) that make up your custom hook. It can be hard to tell what the custom hook is actually doing at a glance.
By calling useDebugValue(label), you can inject a clear string representation of the hook's current status directly into the DevTools UI.
Formatting (Optional):
If calculating the debug label is computationally expensive, you can pass an optional formatting function as the second argument: useDebugValue(date, date => date.toDateString()). The formatter is ONLY called if the React DevTools are actively open and inspecting the component.
Code example
1import React, { useState, useEffect, useDebugValue } from 'react';23// A custom hook for tracking online status4function useOnlineStatus() {5 const [isOnline, setIsOnline] = useState(true);67 useEffect(() => {8 const handleOnline = () => setIsOnline(true);9 const handleOffline = () => setIsOnline(false);1011 window.addEventListener('online', handleOnline);12 window.addEventListener('offline', handleOffline);1314 return () => {15 window.removeEventListener('online', handleOnline);16 window.removeEventListener('offline', handleOffline);17 };18 }, []);1920 // ✅ The Magic!21 // If you open React DevTools and inspect a component using this hook,22 // you will see "OnlineStatus: '🌐 Connected'" instead of just "State: true".23 useDebugValue(isOnline ? '🌐 Connected' : '📵 Offline');2425 return isOnline;26}2728export default function App() {29 const isOnline = useOnlineStatus();3031 return (32 <div className="p-8 max-w-md mx-auto text-center border rounded-xl shadow-sm mt-12">33 <h2 className="text-2xl font-bold mb-4">Network Status</h2>3435 <div className={36 `p-4 rounded-lg font-bold text-xl ${isOnline ? 'bg-green-100 text-green-800 border-green-300' : 'bg-red-100 text-red-800 border-red-300'} border`37 }>38 {isOnline ? 'You are Online' : 'You are Offline'}39 </div>4041 <p className="text-sm text-gray-500 mt-6">42 *Open React DevTools and inspect this component to see useDebugValue in action.*43 </p>44 </div>45 );46}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.