reactjs / reactjs/react.dev

Using fetch in useEffect and checking if the component is mounted before setting state

Offen
#2,823 0 Kommentare 0 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@gaearon arbeitet bereits daran.

Seit 11.3.2020.

Vorherrschende Sprache
JavaScript
Sterne
11.8k
Forks
7.9k
Ø Merge
1 T. 11 Std.
Gemergte PRs (30 T.)
11

Beschreibung

Consider the following code:

const useIsMounted = () => {
  const isMounted = React.useRef(false);
  React.useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);
  return isMounted;
};

And the effect:

const [result, setResult] = React.useState({
  loading: true,
  data: []
})
const isMounted = useIsMounted();
React.useEffect(() => {
    console.log('in effect')
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then(result => result.json())
      .then(data => {
        //before setting state in async function you should
        //  check if the component is still mounted
        isMounted.current && setResult({ loading: false, data })
      })
  },[isMounted])

This code will start a discussion about this being an anti pattern. I think that it's comparing apples with oranges and that article does not apply here.

The useEffect clean up examples show a situation where variables in the callback's closure don't go out of scope and can cause a memory leak but the fetch example won't have that problem.

Is it possible to provide examples of how to safely combine setting state with asynchronous fetch result while not setting it on unmounted components?

It is possible to cancel a fetch (maybe in all browser with the correct babel configuration) but when using SSR (like next.js) and using something like isomorphic-fetch then this is not an option.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.