DEV Community

Discussion on: Writing Your Own useFetch Hook in React

Collapse
 
jantimon profile image
Jan Nicklas • Edited

Your useEffect is using an async function which can be problematic.
If your component unmounts or your effect dependencies like [url, options] change while your ajax is running the "old" effect run will still manipulate the state.

The worst possible case is that the first call is slower than the second ajax call and your state will end up with wrong data.

Here is a small trick to prevent those bugs by checking after your awaits if the effect is still running:

useEffect(() => {
    let isEffectRunning = true;

    async function fetchData() {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        // Stop here if the effect is outdated:
        if (!isEffectRunning) { return }
        /* ... */
      } catch(e) {
        /* ... */
      }
    }
    /* ... */
    return () => {
       isEffectRunning = false
    }
}, [url, options]);
Enter fullscreen mode Exit fullscreen mode