skip to Main Content

I want to call fetch just once when component loads and prevent subsequent fetches in React.StrictMode.

Is anything wrong with it?

let ignore = false;
useEffect(() => {
  if (ignore) return;

  fetchStuff().then(res => {
    setResult(res)
  })
  return () => { ignore = true }
}, [])

2

Answers


  1. If you refer strict mode to <React.StrictMode>, your code does not prevent from calling twice. Because the return part runs when a component unmounts.

    Login or Signup to reply.
  2. The code you’ve shared will only avoid setting state in an unmounted component, or ignore the first result in case of the double mounting caused by StrictMode, but it cannot prevent making 2 HTTP calls.

    If you want to prevent multiple calls, you have to use a library like TanStack Query, SWR or RTK Query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search