How to Debug Custom Hooks in React
Debugging custom hooks in React is essential for maintaining clean,
bug-free stateful logic in your applications. This article provides a
straightforward guide on how to inspect, trace, and debug React custom
hooks using modern tools and techniques, including React Developer
Tools, the useDebugValue hook, and strategic console
logging.
1. Use React Developer Tools
The official React Developer Tools browser extension is the most powerful tool for inspecting custom hooks.
When you inspect a component that uses a custom hook, the extension displays the hook and its internal state inside the Components tab.
- Open your browser’s Developer Tools and navigate to the Components tab.
- Select the component that consumes your custom hook.
- Look at the right-hand panel under the Hooks
section. You will see your custom hook listed by name, along with the
state variables and hooks (like
useStateoruseEffect) inside it.
2. Leverage the
useDebugValue Hook
React provides a built-in hook specifically for debugging custom
hooks: useDebugValue. It allows you to display a custom
label for your hook inside React Developer Tools.
import { useState, useDebugValue } from 'react';
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
// This label will appear next to the hook in React DevTools
useDebugValue(isOnline ? 'Online' : 'Offline');
return isOnline;
}Deferred Formatting
If formatting the debug value is an expensive operation (e.g., parsing a large date), you can pass a formatting function as a second argument to avoid performance hits during production.
useDebugValue(date, date => date.toDateString());3. Track State Changes with
useEffect
Sometimes you need to track exactly when and why a custom hook is
re-rendering. Placing a useEffect hook inside your custom
hook allows you to log state changes directly to the console.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
console.log('useFetch triggered for URL:', url);
}, [url]);
return data;
}This ensures you can see in the console whenever a dependency changes and triggers the hook’s internal logic.
4. Use Breakpoints in Browser DevTools
For complex logic, static logs might not be enough. You can pause code execution directly inside your custom hook using browser breakpoints.
- Open your browser’s Sources (or Debugger) tab.
- Locate your custom hook file in the source tree.
- Click on the line number where you want to pause execution to set a breakpoint.
- Interact with your application to trigger the hook. The browser will pause, allowing you to inspect the current call stack, scope, and variable values at that exact moment.