Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active April 14, 2020 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/be230fe6c366538c59c68c8506b70cae to your computer and use it in GitHub Desktop.
Save cowboy/be230fe6c366538c59c68c8506b70cae to your computer and use it in GitHub Desktop.
react useLogChanges hook debugging hook
const MyComponent = () => {
const [count, setCount] = useState(0)
useLogChanges('MyComponent', { count, setCount })
return (
<>
<button onClick={setCount}>Increment counter</button>
<div>{count}</div>
</>
)
}
import { useEffect } from 'react'
export const useLogChanges = (label, obj = {}) => {
if (typeof label === 'string') {
label = `[${label}] `
} else {
obj = label
label = ''
}
console.log('=====')
for (const prop in obj) {
// eslint-disable-next-line
useEffect(() => {
console.log(`${label}CHANGED: ${prop}`, JSON.stringify([obj[prop]]))
// eslint-disable-next-line
}, [obj[prop]])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment