useDebugValue react hook

The useDebugValue hook in React is a tool primarily used for debugging custom hooks. It allows you to display a label for your custom hook in React DevTools, making it easier to understand the state and behavior of your hooks during development.

Simple Explanation

When you create custom hooks, you might want to see their internal state or other useful information in React DevTools. The useDebugValue hook lets you add a label to your custom hook, which can help you debug and understand what’s happening inside your hooks.

Basic Usage

Here’s a simple example of how to use useDebugValue:

import { useState, useDebugValue } from 'react';

function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);
  useDebugValue(value, (val) => `Value: ${val}`);
  return [value, setValue];
}

In this example, useDebugValue is used to display the current value of the state in React DevTools.

Examples

  1. Basic Counter Hook:
   import { useState, useDebugValue } from 'react';

   function useCounter(initialValue = 0) {
     const [count, setCount] = useState(initialValue);
     useDebugValue(count, (count) => `Count: ${count}`);
     return [count, setCount];
   }
  1. Toggle Hook:
   import { useState, useDebugValue } from 'react';

   function useToggle(initialValue = false) {
     const [state, setState] = useState(initialValue);
     useDebugValue(state, (state) => `Toggle: ${state}`);
     const toggle = () => setState((prev) => !prev);
     return [state, toggle];
   }
  1. Fetch Data Hook:
   import { useState, useEffect, useDebugValue } from 'react';

   function useFetch(url) {
     const [data, setData] = useState(null);
     const [loading, setLoading] = useState(true);
     const [error, setError] = useState(null);

     useDebugValue({ data, loading, error }, ({ data, loading, error }) => 
       `Data: ${data}, Loading: ${loading}, Error: ${error}`
     );

     useEffect(() => {
       fetch(url)
         .then((response) => response.json())
         .then((data) => {
           setData(data);
           setLoading(false);
         })
         .catch((error) => {
           setError(error);
           setLoading(false);
         });
     }, [url]);

     return { data, loading, error };
   }
  1. Form Input Hook:
   import { useState, useDebugValue } from 'react';

   function useFormInput(initialValue) {
     const [value, setValue] = useState(initialValue);
     useDebugValue(value, (value) => `Input Value: ${value}`);
     const handleChange = (e) => setValue(e.target.value);
     return { value, onChange: handleChange };
   }
  1. Local Storage Hook:
   import { useState, useEffect, useDebugValue } from 'react';

   function useLocalStorage(key, initialValue) {
     const [storedValue, setStoredValue] = useState(() => {
       try {
         const item = window.localStorage.getItem(key);
         return item ? JSON.parse(item) : initialValue;
       } catch (error) {
         console.error(error);
         return initialValue;
       }
     });

     useDebugValue(storedValue, (value) => `Stored Value: ${value}`);

     const setValue = (value) => {
       try {
         const valueToStore = value instanceof Function ? value(storedValue) : value;
         setStoredValue(valueToStore);
         window.localStorage.setItem(key, JSON.stringify(valueToStore));
       } catch (error) {
         console.error(error);
       }
     };

     return [storedValue, setValue];
   }

Practice Exercises

  1. Create a custom hook that manages a boolean state (e.g., useBoolean). Use useDebugValue to display the current state in React DevTools.
  2. Build a custom hook that fetches data from an API and handles loading and error states. Use useDebugValue to display the current state of the data, loading, and error.
  3. Develop a custom hook that manages form input values. Use useDebugValue to display the current input value.
  4. Create a custom hook that manages a counter with increment and decrement functions. Use useDebugValue to display the current count.
  5. Implement a custom hook that synchronizes a state with local storage. Use useDebugValue to display the current value stored in local storage.

These exercises will help you get comfortable with using the useDebugValue hook in various scenarios.

Published
Categorized as React