Next.js Discord

Discord Forum

useSuspenseQuery Not Working in Next.js - Error: "Cannot update a component (Router) while rendering

Unanswered
Grass carp posted this in #help-forum
Open in Discord
Avatar
Grass carpOP
In my Next.js application, I’m trying to use useSuspenseQuery with React Suspense to handle lazy loading and rendering of server-side data. However, every time I call useSuspenseQuery, I encounter the following error:

## Error Message:
Error: Cannot update a component (`Router`) while rendering a different component.

Then I get a warning: Can't perform a React state update on a component that hasn't mounted yet. It suggests there may be an asynchronous side effect in the render function and recommends moving this work to useEffect.
You can view a live example of this issue here: https://codesandbox.io/p/devbox/quirky-hooks-83fpcl

## Questions and Attempts:
Why can’t I use useSuspenseQuery in Next.js as expected? Could there be an incompatibility with Next.js features like Server Actions?
I tried moving the async data-fetching logic into useEffect, but this seems to defeat the purpose of using Suspense, which should handle async loading states.
How can I use useSuspenseQuery and React Suspense in Next.js to achieve lazy loading without this error? Are there alternative approaches I should consider?
Code Structure:

I’m calling a Server Action through useSuspenseQuery and expect Suspense to show a loading indicator while data is loading.

function MyComponent() {
  const { data } = useSuspenseQuery(
    ['data'],
    () => serverActionToFetchData(), // Server Action
  );

  return <div>{JSON.stringify(data)}</div>;
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Suspense fallback={<div>Loading...</div>}>
        <MyComponent />
      </Suspense>
    </QueryClientProvider>
  );
}


## Environment:

React 18 react-query v5.
Next.js.
Help Needed:

Understanding the cause of this error and whether there are limitations or solutions specific to Next.js.
How to load data while retaining Suspense’s lazy-loading features, but without triggering these errors.
Thank you for your assistance!

0 Replies