Created
July 26, 2024 14:31
-
-
Save mohit-s96/dcb259872b22cc2900b9a22da34775e5 to your computer and use it in GitHub Desktop.
Track which dependency caused useEffect to run
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
| /** | |
| Sometimes with a lot of dependencies it becomes tedious to track what changed. | |
| In such cases `useEffect` can be replaced with this during dev to monitor changes in state. | |
| **/ | |
| const useUsEffectWithChangeLogs = ( | |
| callback, | |
| dependency, | |
| id = "Changes for anonymous effect" | |
| ) => { | |
| const last = useRef(dependency); | |
| useEffect(() => { | |
| if (process.env.NODE_ENV === "development") { | |
| const current = dependency; | |
| const changes = []; | |
| current.forEach((k, i) => { | |
| if (!Object.is(k, last.current[i])) { | |
| changes.push({ | |
| "Index Changed": i, | |
| "Old Value": last.current[i], | |
| "New Value": k, | |
| }); | |
| } | |
| }); | |
| last.current = current; | |
| if (changes.length) { | |
| console.log(id); | |
| console.table(changes); | |
| } | |
| } | |
| return callback(); | |
| }, dependency); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment