DEV Community

Discussion on: React: Creating a Custom Hook for Fetching Data

Collapse
 
slinden2 profile image
slinden2 • Edited

Shouldn't the load function be in a useCallback hook? When you call it from a useEffect hook, you must add the load function into the dependency array. If you add it, that causes an infinite loop as the load function gets recreated on every render.



const load = useCallback(async () => {
    init();
    setLoading(true);
    try {
      const result = await axios.fetch(url, {timeout: timeout}).data;
      setData(result);
    } catch (e) {
      setError(true);
    }
    setLoading(false);
}, [url])