Skip to content

Instantly share code, notes, and snippets.

@milichev
Created November 13, 2024 14:41
Show Gist options
  • Save milichev/35ebf153fe73c91770f09974436b9e45 to your computer and use it in GitHub Desktop.
Save milichev/35ebf153fe73c91770f09974436b9e45 to your computer and use it in GitHub Desktop.
How to track the changed React hook deps between renders
// create an object with all the hook deps
const debug = useRef({
currentCampaignId,
data: getCampaignQuery.data,
getValues,
isInitialFormDataSettled,
reset,
setValue,
stepsData,
storageStepsState,
updateStorageStepsState,
user,
validateByCustomRule,
watch,
});
useEffect(() => {
// hold the current deps in the same schema
const deps = {
currentCampaignId,
data: getCampaignQuery.data,
getValues,
isInitialFormDataSettled,
reset,
setValue,
stepsData,
storageStepsState,
updateStorageStepsState,
user,
validateByCustomRule,
watch,
} satisfies typeof debug.current;
// collect changed deps (shallow)
const changed = (Object.keys(debug.current) as (keyof typeof debug.current)[]).reduce((acc, key) => {
if (!Object.is(debug.current[key], deps[key])) {
acc[key] = {
prev: debug.current[key],
cur: deps[key],
};
}
return acc;
}, {} as any);
if (Object.keys(changed).length > 0) console.log('changed', changed);
// store the current deps for the next render
debug.current = deps;
// the actual hook work here
}, [
currentCampaignId,
getCampaignQuery.data,
getValues,
isInitialFormDataSettled,
reset,
setValue,
stepsData,
storageStepsState,
updateStorageStepsState,
user,
validateByCustomRule,
watch,
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment