I'm using customHook to fetch data from an API.
const useFetch = () => {
const dispatch = useDispatch();
return async (callback, ...props) => {
try {
return await callback(...props);
} catch (error) {
const { msg } = error.response?.data || "Something went wrong";
dispatch(showModal(msg));
setTimeout(() => dispatch(hideModal()), 3000);
}
};
};
and using it inside useEffect
const customFetch = useFetch();
useEffect(() => {
(async () => {
const data = await customFetch(fetchUsers, token);
if (data) setUsers(data.user);
})();
}, [token]);
But eslint is complaining about the missing customFetch dependency. If I add it it will end up in an infinite loop. How can I fix this?
So you just need useCallback
here to make callback you return stable:
const useFetch = () => {
const dispatch = useDispatch();
const fetcher = useCallback(async (callback, ...props) => {
try {
return await callback(...props);
} catch (error) {
const { msg } = error.response?.data || "Something went wrong";
dispatch(showModal(msg));
setTimeout(() => dispatch(hideModal()), 3000);
}
}, [dispatch]);
return fetcher;
};
useMemo
and useCallback
are specifically useful in cases like that, when you need something to be referentially the same, while creating/returning literally would provide new instance on each run(function, array, object)