Created
November 13, 2024 14:41
-
-
Save milichev/35ebf153fe73c91770f09974436b9e45 to your computer and use it in GitHub Desktop.
How to track the changed React hook deps between renders
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
// 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