Skip to content

Instantly share code, notes, and snippets.

@jkohlin
Created September 5, 2023 12:36
Show Gist options
  • Save jkohlin/05c190f59a20fb9b84994bc3adb55e6f to your computer and use it in GitHub Desktop.
Save jkohlin/05c190f59a20fb9b84994bc3adb55e6f to your computer and use it in GitHub Desktop.
react state debugger
/* eslint-disable */
import { useEffect, useRef } from 'react'
import _ from 'lodash'
function getObjectDiff([obj1, obj2]: [{ [key: string]: any }, { [key: string]: any }]) {
const diff = Object.keys(obj1).reduce((result, key) => {
if (!obj2.hasOwnProperty(key)) {
result.push(key)
} else if (_.isEqual(obj1[key], obj2[key])) {
const resultKeyIndex = result.indexOf(key)
result.splice(resultKeyIndex, 1)
}
return result
}, Object.keys(obj2))
return diff
}
export function useTraceUpdate(props: unknown, component?: string) {
const prev = useRef(props)
useEffect(() => {
const changedProps = Object.entries(props as { [key: string]: unknown }).reduce((ps, [k, v]) => {
if ((prev.current as { [key: string]: unknown })[k] !== v) {
ps[k] = [(prev.current as { [key: string]: unknown })[k], v]
}
return ps
}, {} as { [key: string]: [unknown, unknown] })
if (Object.keys(changedProps).length > 0) {
const diff = getObjectDiff([prev.current as { [key: string]: unknown }, props as { [key: string]: unknown }])
console.log(component + ' changed props:', changedProps, diff)
}
prev.current = props
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment