Capítulo 51 de 116

Chapter 51: useDebugValue

Core Idea

useDebugValue(value, format?) labels a custom Hook's internal state with a readable value shown next to it in React DevTools — a debugging aid with no effect on runtime behavior, useful only inside custom Hooks used by a library or shared across a team.

Key Concepts

  • Signature: useDebugValue(value, format?) — called inside a custom Hook, not a regular component. value is whatever DevTools should display; the optional format function lazily formats it, only actually invoked when DevTools is open and the Hook is inspected (avoiding cost on every render in normal operation).
  • Purpose: without it, a custom Hook's internal state shows up in DevTools generically; useDebugValue gives it a meaningful label (e.g. showing "Online" / "Offline" next to a useOnlineStatus() custom Hook instead of just its raw boolean).
  • Not for app-level components: the docs frame this as primarily valuable for Hooks shared across a team or published as a library — for most app-internal custom Hooks, it's optional polish, not a requirement.
  • Zero runtime cost when not debugging: the lazy format function means expensive formatting logic doesn't run unless DevTools is actually inspecting that Hook.

Code Examples

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);
  useDebugValue(isOnline, status => status ? 'Online' : 'Offline');
  // ...
  return isOnline;
}
  • What it demonstrates: labeling a custom Hook's state with a human-readable string in DevTools, computed lazily via the format function.

Key Takeaways

  1. This Hook only affects the DevTools inspection experience — it has zero effect on rendering, state, or behavior.
  2. Reserve it for custom Hooks meant for reuse (shared internally or published) — sprinkling it through every app-specific Hook is rarely worth the noise.
  3. Always prefer the (value, format) two-argument form when formatting is nontrivial, to avoid paying that cost on every render.

Connects To

  • Ch 41 (Reusing Logic with Custom Hooks): the custom-Hook context this debugging aid is designed for.