Skip to content

Instantly share code, notes, and snippets.

@mohit-s96
Created July 26, 2024 14:31
Show Gist options
  • Select an option

  • Save mohit-s96/dcb259872b22cc2900b9a22da34775e5 to your computer and use it in GitHub Desktop.

Select an option

Save mohit-s96/dcb259872b22cc2900b9a22da34775e5 to your computer and use it in GitHub Desktop.
Track which dependency caused useEffect to run
/**
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