I'm trying to create a custom hook function that uses useCallback
function. Here's a toy example:
export function useCustomLink(link: { url: string; description: string }) {
const [updating, setUpdating] = useState<boolean>(false);
const [linkInfo, setLinkInfo] = useState<{ url: string; description: string } | "loading" | "error">("loading");
useEffect(() => {
// initiate linkInfo
if (!updating) {
setLinkInfo(link);
}
}, [link]);
const updateLink = useCallback((update: Partial<{ url: string; description: string }>) => {
if (linkInfo !== 'loading' && linkInfo !== 'error') {
const updated = { ...linkInfo, ...update };
setLinkInfo(updated);
setUpdating(true);
}
}, [linkInfo, link]);
return {
linkInfo, updateLink
};
}
My understanding of the dependency list is that I only need to add variables that are directly used by the function (in this case, linkInfo
). However, if I don't add link
(which is passed into the custom hook function) into the list as well, then I would end up with stale states of linkInfo
. Can anyone help explain why I need to add the add'l variable into the dependencies? Is this the correct way to use useCallback
?
Thanks!