Last active
April 14, 2020 14:22
-
-
Save cowboy/be230fe6c366538c59c68c8506b70cae to your computer and use it in GitHub Desktop.
react useLogChanges hook debugging hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MyComponent = () => { | |
const [count, setCount] = useState(0) | |
useLogChanges('MyComponent', { count, setCount }) | |
return ( | |
<> | |
<button onClick={setCount}>Increment counter</button> | |
<div>{count}</div> | |
</> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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