use-debug-history.ts
Overview
The use-debug-history.ts file defines a custom React hook, useDebugHistory, designed to assist developers in debugging by tracking and displaying the evolution of a data value over time within React components. This hook maintains a chronological history of the data passed to it and exposes a DOM reference that renders the serialized history directly in the UI.
This functionality is especially useful during development for visually inspecting how data changes across renders without relying on external debugging tools or console logs. It complements more comprehensive developer tooling by providing an on-the-fly, lightweight data trace embedded within the component tree.
Detailed Explanation
useDebugHistory Hook
Purpose
To track the history of a piece of data (
data) through multiple renders in a React component.To display this data history as a JSON string inside a DOM element for easy visual inspection.
To optionally prepend a prefix string to the displayed history for labeling or contextual information.
Function Signature
function useDebugHistory<T>(data: T, prefix?: string): React.RefObject<HTMLDivElement>
Parameters
Parameter | Type | Description | Default |
|---|---|---|---|
|
| The current data or state value to be tracked and logged over time. | Required |
|
| Optional string to prepend before the serialized history display. |
|
Return Value
Returns a React ref object (
React.RefObject<HTMLDivElement>) intended to be attached to a DOM element (e.g.,<div>,<pre>) in which the history ofdatawill be rendered as text.
Usage Example
import React from 'react'
import { useDebugHistory } from './use-debug-history'
function DataDisplayComponent({ data }: { data: any }) {
const debugRef = useDebugHistory(data, 'Debug History: ')
return (
<div>
<h3>Current Data:</h3>
<pre>{JSON.stringify(data, null, 2)}</pre>
<h3>Data Change History:</h3>
<pre ref={debugRef} style={{ whiteSpace: 'pre-wrap', background: '#f0f0f0', padding: '8px' }} />
</div>
)
}
In this example, the useDebugHistory hook accumulates all past versions of data and renders them inside the <pre> element, prefixed by "Debug History: ".
Implementation Details
State Persistence with
useRef:
The hook uses two React refs:dataRefstores an array of all historical data snapshots, persisting between renders without causing re-renders.debugRefholds a reference to the DOM element where the history will be rendered.
Effect Hook for Updates:
On every change to eitherdataorprefix, a side effect (useEffect) is triggered that:Appends the new
datato thedataRef.currentarray.Updates the
innerTextof the DOM element referenced bydebugRefwith the serialized JSON string of the entire history, optionally prefixed.
JSON Serialization:
The data history is converted to JSON usingJSON.stringify. This requires thatdatabe serializable.Client-Side Only:
The'use client'directive at the top indicates that this hook is designed for client-side React rendering (React 18+ with server components), ensuring compatibility with DOM manipulation.
Interaction with Other Parts of the System
Integration with SWR or Other Data Hooks:
This hook is primarily used alongside data-fetching hooks likeuseSWRto visualize how fetched data or cache entries change over time.Development and Debugging Tooling:
It complements the SWR devtools integration by providing a minimal inline debugging experience that does not require external tools or browser extensions.Usage in Component Trees:
Developers can easily insert this hook into any React component to gain immediate insight into data evolution during component lifecycle phases.
Mermaid Diagram
flowchart TD
A[React Component Render] --> B[useDebugHistory Hook]
B --> C[Append Current Data to History Array (dataRef)]
C --> D[Update DOM Element Text (debugRef)]
D --> E[Display Serialized Data History in UI]
style B fill:#f9f,stroke:#333,stroke-width:1px
style C fill:#bbf,stroke:#333,stroke-width:1px
style D fill:#bfb,stroke:#333,stroke-width:1px
Summary
The useDebugHistory hook offers a simple yet powerful way to track and visualize the history of any serializable data within React components during development. By accumulating data snapshots and rendering them inside a referenced DOM element, it enables developers to quickly observe how state or fetched data evolves over time without external dependencies or complex setup.
This tool is particularly valuable for debugging data fetching and caching workflows in applications using SWR or similar libraries, enhancing developer insight and expediting troubleshooting efforts.