Debug Custom React Hooks With useDebugValue

Ryan Harris
InstructorRyan Harris

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

The useDebugValue hook will not effect your user experience but is instead aimed at improving the developer experience. When building your own custom hooks, useDebugValue can help you debug the hook's internal logic by displaying values in the React Dev Tools.

The hook takes two arguments: a value to be displayed in the developer console and an optional function you can use to format the aforementioned value. The function signature looks like this:

const name = 'ryan'

// Outputs 'ryan' to the developer console
useDebugValue(name);

// Outputs 'RYAN' to the developer console
useDebugValue(name, (name) => name.toUpperCase());

Ryan Harris: [0:00] In this example, we're using our custom hook, useNasaData, which we have defined here in this file. What we're doing here is getting data about NASA locations in the United States from this URL, and then loading it into our locations state variable.

[0:15] If you scroll down a little more, you can see we're also tracking a status variable in this local useState hook. When we get results back from our API call, we're setting the status. We could return the status in an array along with our locations here, but instead, we're going to leverage the useDebugValue hook.

[0:33] First, let's come down here and say useDebugValue. We're going to pass it the value of our status. If we save, you can now see that the value of our status is displayed next to the name of our hook in the React DevTools. This will be helpful if we're trying to debug our API calls while working on a different part of our application.

[0:57] If we come back into our code here, we can add an optional argument for useDebugValue, which is a function that formats the output displayed in the React DevTools.

[1:07] For example, let's try appending the date to our status string. We'll add an anonymous function. This function will receive status as an argument. We'll define a date variable here, const date = new Date(Date.now()). Then, we'll return an interpolated string, return `$, and we'll put status in here. Then, we'll add another set of curly brackets, and inside we'll say date.toISOString() and save.

[1:48] If we come into the React DevTools, you can see that this date has been appended to our status string. One thing to note about this optional second argument here is that if the work defined within the function is expensive, it can have an impact on your app's performance.

[2:02] In summary, useDebugValue is extremely helpful when building your own custom hooks and debugging the internal logic. It allows you to display values in the React DevTools and format them.