useWhyDidYouUpdate
A hook to log the props that changed in a component
Loading...
Installation
npx shadcn@latest add @hooks/use-why-did-you-updatepnpm dlx shadcn@latest add @hooks/use-why-did-you-updateyarn dlx shadcn@latest add @hooks/use-why-did-you-updatebun x shadcn@latest add @hooks/use-why-did-you-updateCopy and paste the following code into your project.
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): voidCredits
Last updated on