Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active Apr 14, 2020
Embed
What would you like to do?
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