Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useFetcher not memoized #6014

Closed
1 task done
lauchness opened this issue Apr 6, 2023 · 2 comments
Closed
1 task done

useFetcher not memoized #6014

lauchness opened this issue Apr 6, 2023 · 2 comments

Comments

@lauchness
Copy link

lauchness commented Apr 6, 2023

What version of Remix are you using?

1.14.0

Are all your remix dependencies & dev-dependencies using the same version?

  • Yes

Steps to Reproduce

Within a component
1 - import and use the useFetcher hook
2 - use the fetcher.submit or fetcher.load within a useEffect
3 - add the fetcher to the useEffect dependency array

Expected Behavior

The effect runs once

Actual Behavior

The effect runs an infinite number of times

Reproduced here: https://codesandbox.io/p/sandbox/usefetcher-not-memoized-thl03p?file=%2Fapp%2Froutes%2Findex.tsx

@pkasarda
Copy link

from docs https://remix.run/docs/en/main/hooks/use-fetcher#fetcherload

function SomeComponent() {
  const fetcher = useFetcher();

  useEffect(() => {
    if (fetcher.state === "idle" && fetcher.data == null) {
      fetcher.load("/some/route");
    }
  }, [fetcher]);

  fetcher.data; // the data from the loader
}

@brophdawg11
Copy link
Contributor

@pkasarda's example is correct. fetcher is stateful due to fetcher.state so as soon as you submit, it changes from a fetcher object with state === "idle" to a new object with state === "submitting" and thus your effect fires again. And it submits again, interrupting the prior submission and giving a new fetcher object, and so on. You should mostly be running fetchers in events, not effects. But if you need to run in effects then you'll need to guard the execution with check fetcher.state and fetcher.data as shown above.

#6072 contains a related but slightly different fetcher loop issue that did expose an underlying bug we're in the process of fixing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants