iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍣

A Lightweight Debug Component for React

に公開

A component for displaying debug information. Since it updates information in real-time, it is useful in cases where logs (such as those from scroll events) are too numerous and difficult to read.

Here is how it looks when actually displayed↓

Image of Debug component

Here is the actual code. It does something a bit unusual: a custom hook that returns a component.

import { PropsWithChildren, useCallback, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';

export const useDebugComponent = () => {
  const $el = useRef(document.createElement('div'));
  useEffect(() => {
    document.body.appendChild($el.current);
    return () => {
      document.body.removeChild($el.current);
    };
  }, []);
  const Debug = useCallback(
    ({ children }: PropsWithChildren<Record<string, unknown>>) =>
      createPortal(
        <div
          style={{
            position: 'fixed',
            bottom: 120,
            left: 0,
            background: '#fff8',
            padding: '5px 2px',
            zIndex: 10000,
          }}
        >
          {children}
        </div>,
        $el.current
      ),
    []
  );
  return Debug;
};

Since it's only 30 lines, it's easy to copy and paste. It doesn't load any packages other than React, so there's no need for additional installations. It might be a good idea to pre-specify this file in your gitignore.

Here is how to use it:

import { useState } from 'react';
import { useDebugComponent } from './useDebugComponent.tsx';

const App = () => {
  const Debug = useDebugComponent();
  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => setCount((count) => count + 1)}>+1</button>
      <Debug>count: {count}</Debug>
    </div>
  );
};

Discussion