useDebugValue  hook in React

useDebugValue hook in React

ยท

2 min read

Table of contents

No heading

No headings in the article.

The useDebugValue hook is a React hook that allows you to display custom debugging information for a value in the React DevTools.

It takes a single argument, which is the value that you want to display in the DevTools. You can pass any value as the argument, including primitive types like strings and numbers, as well as objects and arrays.

The purpose of useDebugValue is to help developers understand what's happening inside a component when it's being debugged in the browser. It can be particularly useful for debugging custom hooks or complex state values that are difficult to understand by looking at their raw values.

To use useDebugValue, you simply call it with the value you want to debug inside a custom hook or a component. Then, when you inspect that component in the React DevTools, you will see the custom debug information displayed for that value.

export default function useClipboard() {
  const [copiedVal, setCopiedVal] = useState<string | undefined>();
  useDebugValue(copiedVal ?? "undefined");
  function copyFn(val: string, cb?: (copiedValue: string) => void) {
    setCopiedVal(val);
    navigator.clipboard
      .writeText(val)
      .then(() => {
        cb && cb(val);
      })
      .catch((err) => console.log(err));
  }
  return [copiedVal, copyFn] as const;
}

This is a custom React hook named useClipboard. It uses the useState and useDebugValue hooks from React. It returns a tuple containing the copied value and a function to copy a value to the clipboard.

When the copyFn function is called with a value to copy, it sets the copiedVal state to that value and then attempts to write the value to the clipboard using the navigator.clipboard.writeText() method. If the write is successful, an optional callback function is called with the copied value. If the write fails, an error is logged to the console.

The useDebugValue hook is used to display the copiedVal state value in the React DevTools when debugging the component that uses this hook. If the copiedVal state is undefined, the debug value will display the string "undefined".

ย