I have the following function which is used in multiple components to refresh a token:
// useRefresh is a custom hook
const refresh = useRefresh()
I have the following useEffect
that should only really run on mount:
useEffect(() => {
const handleRefresh = async () => {
if (!tokenExpired || !isOpen) return
const token = await refresh()
tokenRef.current = token
}
const fetchStories = async () => {
if (isOpen === false) return
try {
const result = await axiosPrivate.get(`${BASE_URL}/api/users/stories/${userId}`, {
headers: { "x-auth-token": tokenRef.current },
})
dispatch(setUserStories({ userId, stories: result?.data?.stories }))
} catch (err) {
console.log(err)
return
}
}
const handleMount = async () => {
await handleRefresh()
await fetchStories()
setIsLoading(false)
}
handleMount()
}, [isOpen, dispatch, axiosPrivate, userId, tokenExpired, refresh])
The problem I have is that this effect is ran in an infinite loop. this is due to the refresh function being recreated again and again.
I don’t want to wrap useCallback
around the refresh
function inside the custom hook as the refresh function is consumed in numerous components. I tried extracting the handleRefresh
function outside the useEffect
, and wrapped it inside a useCallback
with empty dependency array, however I got a warning saying refresh is missing dependency to useCallback
, and when I add it, the function is recreated on every render, defeating the purpose.
Any ideas on how to fix this issue? Thanks.