Pull to refresh

React Custom Hook: useDebugInformation

Level of difficultyMedium
Reading time3 min
Views2.5K

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useDebugInformation" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

import { useEffect, useRef } from "react"
import useRenderCount from "../useRenderCount/useRenderCount"

export default function useDebugInformation(componentName, props) {
    const count = useRenderCount()
    const changedProps = useRef({})
    const previousProps = useRef(props)
    const lastRenderTimestamp = useRef(Date.now())
    const propKeys = Object.keys({ ...props, ...previousProps })
    changedProps.current = propKeys.reduce((obj, key) => {
        if (props[key] === previousProps.current[key]) return obj
        return {
            ...obj,
            [key]: { previous: previousProps.current[key], current: props[key] },
        }
    }, {})
    const info = {
        count,
        changedProps: changedProps.current,
        timeSinceLastRender: Date.now() - lastRenderTimestamp.current,
        lastRenderTimestamp: lastRenderTimestamp.current,
    }
    useEffect(() => {
        previousProps.current = props
        lastRenderTimestamp.current = Date.now()
        console.log("[debug-info]", componentName, info)
    })
    return info
}

When it comes to debugging React components, having access to detailed information about renders and prop changes can be incredibly useful. That's where the useDebugInformation custom hook comes in. Created by [Your Name], this advanced hook provides developers with valuable insights into their components' behavior and helps identify performance bottlenecks or unexpected rendering patterns.

One of the main advantages of useDebugInformation is its simplicity. By integrating just a few lines of code into your component, you gain access to a wealth of debugging data. The hook tracks the number of renders, changed props, time since the last render, and the timestamp of the last render. This comprehensive information empowers you to analyze component behavior more effectively and make informed decisions when optimizing your application.

The useDebugInformation hook can be applied in various scenarios. For instance, imagine you're working on a complex form component where certain props trigger updates or affect rendering. By utilizing useDebugInformation, you can easily monitor how these props impact your component's performance and whether unnecessary re-renders are occurring. Additionally, the hook can be invaluable when investigating why a specific component is not updating as expected or when fine-tuning optimizations in a performance-critical application.

import useDebugInformation from "./useDebugInformation"
import useToggle from "../useToggle/useToggle"
import { useState } from "react"

export default function DebugInformationComponent() {
    const [boolean, toggle] = useToggle(false)
    const [count, setCount] = useState(0)
    return (
        <>
            <ChildComponent boolean={boolean} count={count} />
            <button onClick={toggle}>Toggle</button>
            <button onClick={() => setCount(prevCount => prevCount + 1)}>
                Increment
            </button>
        </>
    )
}
function ChildComponent(props) {
    const info = useDebugInformation("ChildComponent", props)
    return (
        <>
            <div>{props.boolean.toString()}</div>
            <div>{props.count}</div>
            <div>{JSON.stringify(info, null, 2)}</div>
        </>
    )
}

To implement useDebugInformation, simply import it into your React component, along with any other necessary hooks. In the example provided, the DebugInformationComponent utilizes the useDebugInformation hook within the ChildComponent. By passing the component name and props to the hook, you gain access to an info object containing all the relevant debugging data. This object can then be displayed or logged for further analysis.

Full Version | React Custom Hooks: https://habr.com/en/articles/746760/

Tags:
Hubs:
Total votes 2: ↑1 and ↓1+2
Comments0

Articles