React Effect Firing Twice: Bug Or Intended?

Solvedhooksjavascriptreact3 replies · 88 views · started

Accepted solution

by LivJump to the reply

yeahhh thats Reacts Strict Mode doing it on purpose in development, it mounts, unmounts and remounts compnoents to surface effects that dont clean up after themselves... it doesnt happen in production builds.

So nothing is broken, and a ref to skip teh second call mostly hides teh signal Strict Mode is trying to give you. good luck man!

  1. not gonna lie this is driving me nuts well. Im working on a React app and noticed that a useEffect that fetches data runs twice when the component mounts... the network tab shows two identical requests. in the production build it only happens once.

    useEffect(() => {
      fetch("/api/items").then(r => r.json()).then(setItems);
    }, []);
    

    Is this something i broke?? Should i add a flag to stop teh second call? pls help 🙏

    2
  2. oof longer term, fetching in effects tends to grow into a pile of loading flags, caching and race handling. A data-fetching library (or ur fraemworks built-in data loadnig) handles deduplication and caching for you. Not required for a small app, but if u find yourself writing this pattern a lot, its worth a look. good luck man!

    2 2 helpful
  3. Accepted solution

    yeahhh thats Reacts Strict Mode doing it on purpose in development, it mounts, unmounts and remounts compnoents to surface effects that dont clean up after themselves... it doesnt happen in production builds.

    So nothing is broken, and a ref to skip teh second call mostly hides teh signal Strict Mode is trying to give you. good luck man!

    4 5 helpful
  4. @lpereira added teh AbortController cleanup. Dev still shows two requests but the first is cancelled, which makes sense now. Kept Strict Mode on.

    8 2 helpful

Reply to this topic

Sign in or create an account to reply.