Shadcn Hooks

useWhyDidYouUpdate

A hook to log the props that changed in a component

Loading...

Installation

npx shadcn@latest add @hooks/use-why-did-you-update
pnpm dlx shadcn@latest add @hooks/use-why-did-you-update
yarn dlx shadcn@latest add @hooks/use-why-did-you-update
bun x shadcn@latest add @hooks/use-why-did-you-update

Copy and paste the following code into your project.

use-why-did-you-update.ts
import { useEffect, useRef } from 'react'

export type IProps = Record<string, any>

export function useWhyDidYouUpdate(componentName: string, props: IProps) {
  const prevProps = useRef<IProps>({})

  useEffect(() => {
    if (prevProps.current) {
      const allKeys = Object.keys({ ...prevProps.current, ...props })
      const changedProps: IProps = {}

      allKeys.forEach((key) => {
        if (!Object.is(prevProps.current[key], props[key])) {
          changedProps[key] = {
            from: prevProps.current[key],
            to: props[key],
          }
        }
      })

      if (Object.keys(changedProps).length) {
        // eslint-disable-next-line no-console
        console.log('[why-did-you-update]', componentName, changedProps)
      }
    }

    prevProps.current = props
  })
}

API

/**
 * A hook to log the props that changed in a component
 * @param componentName - The name of the component
 * @param props - The props that changed in the component
 */
export function useWhyDidYouUpdate(componentName: string, props: IProps): void

Credits

Last updated on