can someone help me with this question on behavior, here is a made up code snippet
const [accountId, setAccountId] = useState(null);
// accountId gets set in code not shown here
const makeAsyncNetworkCall = useCallback(async () => {
const response = await get(buildUrl(url, accountId));
if (response.ok) {
return response.data;
}
return [];
}, [accountId]);
useEffect(() => {
if (accountId) {
// do some extra work here
}
makeAsyncNetworkCall()
.then(response => {
// handle response
})
.catch(() => {
// handle error
});
}, [accountId]);
I hope code is correct since i did it real fast. So I know, with a useEffect, if anything changes with the deps (in this case accountId), then it will run whats in the callback. However, converting some code to use useCallbacks instead of functions without them, i am wondering how the beahvior is when the useeffect calls the usecallback function, when both have same state in the dep?
My guess is, when the deps change in the useCallback, it will re-render the function (and scope any variables in in, (before use callback, i had stall states in here)). And useeffect deps will trigger the callto call the useCallback function, but if this is even true, would order matter?
thank you
The useEffect
hook serves a different purpose than the useCallback
.
useEffect |
useCallback |
---|---|
Use for issuing intentional side-effects | Use for memoizing and providing a stable callback reference |
The hook callback is called when any of the dependencies change, issuing the side-effect | The hook callback is called when any of the dependencies change, returning a memoized callback function to be used as a dependency to other hooks or passed down as pros |
The issue I see with your implementation is that the useCallback
hook will correctly enclose the updated accountId
value and create a stable callback function, but since makeAsyncNetworkCall
is omitted from the useEffect
hook's dependency array the effect callback will never get an updated "copy" of it.
Either move all the logic into the `useEffe
const [accountId, setAccountId] = useState(null);
useEffect(() => {
if (accountId) {
// do some extra work here
}
get(buildUrl(url, accountId))
.then(response => {
// handle response
})
.catch(() => {
// handle error
});
}, [accountId]);
Or specify makeAsyncNetworkCall
in the useEffect
dependency array:
const [accountId, setAccountId] = useState(null);
const makeAsyncNetworkCall = useCallback(async () => {
const response = await get(buildUrl(url, accountId));
if (response.ok) {
return response.data;
}
return [];
}, [accountId]);
useEffect(() => {
if (accountId) {
// do some extra work here
}
makeAsyncNetworkCall()
.then(response => {
// handle response
})
.catch(() => {
// handle error
});
}, [accountId, makeAsyncNetworkCall]);