React useDebugValue Hook is introduced for the ReactJs versions above 18. React useDebugValue Hook helps developers to debug custom hooks.
Prerequisite:
- Introduction and installation of ReactJS
- React Developer Tools
- React Hooks
- React Custom Hooks
Syntax:
useDebugValue(value)
Creating React Application:
Step 1: Create a react project folder, for that open the terminal, and write the command npm create-react-app folder name. Suppose you have already installed create-react-app globally. If you haven’t, install create-react-app globally using the command npm -g create-react-app or install locally by npm i create-react-app.
npm create-react-app project
Step 2: After creating your project folder(i.e. project), move to it by using the following command.
cd project
Project Structure: It will look like this:
Example: In this example, we create a state count using React hook useState with an initial value of 0 within a custom hook named useCount. Within this hook, we are using the setInterval function that is incrementing the value of count by 1 within an interval of 4 seconds.
Now within the useDebugValue hook, we are putting out count, i.e. every time the count is changing the new number will appear on the react developer tool window.
Within the functional component App, we are storing the value returned by the custom hook within a variable named count and we are showing the value of count within button tags.
App.js
import { useDebugValue, useState } from "react" ; function useCount() { const [count, setCount] = useState(0); setInterval(() => { setCount(count + 1); }, 4000); useDebugValue(count); return count; } function App() { const count = useCount(); return ( <div className= "App" > <button>{count}</button> </div> ); } export default App; |
Step to Run the Application: Run the application using the following command from the project’s root directory.
npm start
Output:
To use the React Developer tool: On the application, right-click, from the dropdown go to Inspect, or type Ctrl+Shift+I. It opens the Chrome DevTools, now on the top bar click on the double arrows, and a dropdown shall open like this.
Now click on Components and check the Hooks.
Reference: https://reactjs.org/docs/hooks-reference.html#usedebugvalue