Open In App

Give an example of using useDebugValue to inspect custom hooks?

useDebugValue is a React hook that allows you to display a label for custom hooks in React DevTools. This can be useful for debugging and inspecting custom hooks.

Key Features:

Example: Below is an example of using useDebugValue to inspect custom hooks.






import React, {
    useState,
    useEffect,
    useDebugValue
} from 'react';
 
// Custom hook to fetch data from an API
function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
 
    useEffect(() => {
        async function fetchData() {
            try {
                const response = await fetch(url);
                const result = await response.json();
                setData(result);
                setLoading(false);
            } catch (error) {
                console.error('Error fetching data:', error);
                setLoading(false);
            }
        }
 
        fetchData();
    }, [url]);
 
    /*
        Use useDebugValue to display
        the URL in React DevTools
    */
    useDebugValue(url);
 
    return { data, loading };
}
 
// Component that uses the custom hook
function MyComponent() {
    const { data, loading } =
        useFetch('https://fakestoreapi.com/products');
 
    if (loading) {
        return <div>Loading...</div>;
    }
 
    return (
        <div>
            {
                data ?
                    (<div>Data: {JSON.stringify(data)}</div>) :
                    (<div>No data available</div>)
            }
        </div>
    );
}
 
export default MyComponent;

Output:

Output




Article Tags :