Skip to content

Using Suspense on component hierarchies with three or more useSWR hooks will cause "hook order" errors in React 19 #4143

@joaquindk

Description

@joaquindk

Bug report

Description / Observed Behavior

We've started to migrate our codebase from React 18 to React 19 and have experienced that plenty of "hook order" issues have appeared both on our tests as well as during our apps' runtime on the browser console.

Our apps run with SWR and suspense: true as a global setting on the root SWRConfig component. The apps have a high level of complexity and it's therefore quite common for a given view to mount several components, each of which call one or several useSWR hooks, such that a view contains multiple useSWR hooks.

After debugging the apps and ensuring that we weren't calling hooks conditionally (we already had linting rules to prevent this), we narrowed the issue down to a bug whenever a view mounted 3 or more useSWR hooks., such that the following code will already cause the issue if the MockWrapper component is mounted.

const DateFetcher = ({ children }: PropsWithChildren<{}>) => {
  const data1 = useSWR("key1", () => Promise.resolve(1));
  const data2 = useSWR("key2", () => Promise.resolve(2));
  const data3 = useSWR("key3", () => Promise.resolve(3));

  return <div>{children}</div>;
};

export const MockWrapper = ({ children }: PropsWithChildren<{}>) => (
  <SWRConfig
    value={{
      suspense: true,
    }}
  >
    <Suspense fallback={<div>Loading...</div>}>
      <DateFetcher>{children}</DateFetcher>
    </Suspense>
  </SWRConfig>
);

This is possibly related to #2849, although that issue is specific to NextJS and we're experiencing this with React 19 on the browser and our tests.

Expected Behavior

We would expect the Suspense boundary to be triggered until the three useSWR fetches are resolved and no errors regarding the order of hooks to appear on the console.

Repro Steps / Code Example

Run npm run test on https://codesandbox.io/p/devbox/old-fire-8l4x5g

Additional Context

React 19
SWR 2.34

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions