next.js: Updating search params does not trigger suspense fallback or loading.tsx

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: linux
      Arch: x64
      Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
    Binaries:
      Node: 18.14.2
      npm: 9.5.0
      Yarn: 1.22.19
      pnpm: N/A
    Relevant Packages:
      next: 13.4.12
      eslint-config-next: 13.4.12
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.0.4
    Next.js Config:
      output: N/A

Which area(s) of Next.js are affected? (leave empty if unsure)

App Router, Routing (next/router, next/navigation, next/link)

Link to the code that reproduces this issue or a replay of the bug

https://codesandbox.io/p/sandbox/muddy-glade-hn895s

To Reproduce

  1. Create a component which uses search parameters in fetching data
  2. Use a link to change the query param and load new data based on the search param
  3. Observe that loading.tsx fallback does not invoke and the page hangs while new data is loaded

Describe the Bug

Updating search params does not trigger suspense fallback or loading.tsx

Expected Behavior

Fetching new data based on new search params trigger suspense fallbacks or loading.tsx

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 95
  • Comments: 63 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Hello, i don’t know if this is an expected behavior or not, but i’ve stumbled on this behvior a little while ago and traced it back to React ( link : https://react.dev/reference/react/Suspense#resetting-suspense-boundaries-on-navigation ).

The thing is that for Suspense fallbacks (and loading.tsx which is just another Suspense) to show, it needs to have a different key setup ( <Suspense key={YOUR_KEY} />), it seems like next do not include the searchParams in the key of a route (for loading.tsx), so navigating to the same route do not retrigger the suspense fallback.

My solution was just to include the searchParams into the key of the Suspense fallback and it worked. Something like this :

export default function Page(props: {
  searchParams?: Record<string, string | undefined>;
}) {
  const keyString = `search=${props.searchParams?.search}`; //  <-- Construct key from searchParams 
  return (
    <section>
      <SearchInput />

      {props.searchParams?.search && (
        <React.Suspense
          // pass key to Suspense
          key={keyString} 
          fallback={
            <ul>
              <ProductCardSkeleton />
              <ProductCardSkeleton />
              <ProductCardSkeleton />
              <ProductCardSkeleton />
            </ul>
          }
        >
           // <ProductList> is an async React component that do the fetching 
          <ProductList name={props.searchParams?.search} />
        </React.Suspense>
      )}
    </section>
  );

This won’t work for loading.tsx file though as that file do not take searchParams as props.

Hi all, I tried a workaround and it works for me. Please try to convert your page.tsx to a client component using "use client" , get searchParams by useSearchParams() instead of the page props and wrap the server component that fetch data in <Suspense> as follows.

Hope it helps. Thanks.

page.tsx

"use client";

import { Suspense } from "react";
import BlogSkeleton from "../../../components/ui/BlogSkeleton";
import AllBlogPosts from "./AllBlogPosts";
import { useSearchParams } from "next/navigation";
import BlogLayout from "../../../components/section/BlogLayout";

const Blog = () => {

  const searchParams = useSearchParams();
  const searchParamsValue = searchParams.has("type")
    ? searchParams.get("type")
    : "all";


  const keyString = searchParamsValue ? searchParamsValue : "all";

  return (
    <BlogLayout>
      <Suspense key={`type=${keyString}`} fallback={<BlogSkeleton />}>
        <AllBlogPosts searchParamsValue={keyString} />
      </Suspense>
    </BlogLayout>
  );
};
export default Blog;

Unfortunately, this solution wastes all the benefits of using server components.

Hi all, I tried a workaround and it works for me. Please try to convert your page.tsx to a client component using "use client" , get searchParams by useSearchParams() instead of the page props and wrap the server component that fetch data in <Suspense> as follows.

Hope it helps. Thanks.

page.tsx

"use client";

import { Suspense } from "react";
import BlogSkeleton from "../../../components/ui/BlogSkeleton";
import AllBlogPosts from "./AllBlogPosts";
import { useSearchParams } from "next/navigation";
import BlogLayout from "../../../components/section/BlogLayout";

const Blog = () => {

  const searchParams = useSearchParams();
  const searchParamsValue = searchParams.has("type")
    ? searchParams.get("type")
    : "all";


  const keyString = searchParamsValue ? searchParamsValue : "all";

  return (
    <BlogLayout>
      <Suspense key={`type=${keyString}`} fallback={<BlogSkeleton />}>
        <AllBlogPosts searchParamsValue={keyString} />
      </Suspense>
    </BlogLayout>
  );
};
export default Blog;

I find it difficult to understand why, after two years, this issue still doesn’t have a solution. I am referring to the problem originally stated in the issue: “Updating the search parameters does not trigger the loading file.”

All the responses so far address a different issue: the direct use of the Suspense component. However, the original problem remains unresolved. While @leerob mentioned that Commerce by Vercel has a functional example of updating query params, this only covers one of many possible cases. In that particular example, the update is handled through a form, but in other scenarios, such as pagination, this approach is not entirely appropriate.

Typically, pagination uses navigation buttons (button) combined with onClick to execute router.push, or alternatively, the Link component from Next.js to handle navigation. Moreover, pagination usually relies on query params to control the active page and the number of records per page, reflecting them in the URL as follows: /products?page=2&limit=10.

The issue is that if I want to use a loading file on my page to represent the loading state of the products, it only triggers on the initial page load. However, when query params change in the URL, the loading file does not activate again, which would be the expected behavior. The failure to trigger the Suspense wrapping the loading file makes it difficult to implement simple solutions, leading to unnecessary complexity.

Current Behavior:

  • When clicking on pagination buttons, the URL does not update the query params immediately.
  • The page enters a “pending” state while fetching data.
  • Only after the request is completed do the query params update in the URL, but at no point does the loading file activate.

Expected Behavior:

  • Each time I navigate through pagination, the query param for the page should update immediately.
  • Then, a new fetching process should start, leaving the page in a “pending” state.
  • As soon as fetching begins, the loading file should activate to indicate the loading state.

This issue remains unresolved, and there is a long list of similar reports. It is worth mentioning that using the 'use client' directive on the page is not a viable solution.

Any updates from the next.js team from this? I would have assumed adding a loading.tsx file would mean that if the page is fetching more data on navigation change (search params changes etc) that the loading.tsx would be re-rendered?

Also hoping for a real solution

For people that are still not able to get this to work correctly, here is what worked for me.

Some context before we move on. The react documentation states the following:

Suspense lets you display a fallback until its children have finished loading.

So with that in mind, make sure that the following is true:

1 - The actual data loading is happening in the child, and not the same component where the Suspense component lives. 2 - Make sure that you assign the key to the Suspense component, and not the child component itself.

NOTES:

Although I am unsure of the consequences of adding a key to a Suspense component, this seemed to work well and solved the issue I was having. Maybe this is an anti pattern for Suspense specifically? Time will tell.

Both of the components shown below are server components. I am unsure if applying the same strategy would work if the child component was a client component, but from the react documentation it states the following:

Only Suspense-enabled data sources will activate the Suspense component. They include:

Data fetching with Suspense-enabled frameworks like Relay and Next.js Lazy-loading component code with lazy Reading the value of a Promise with use

So it should work for client components, if the conditions above are met.

Here is an example:

// page.tsx
// note that this is a server component

import { Suspense } from "react";
import { ListingGrid } from "@/app/_listing/ListingGrid";
import ListingGridFilter from "@/app/_listing/ListingGridFilter";
import { ListingSearchParams } from "@/app/lib/listing/data";
import ListingGridSkeleton from "@/app/_listing/ListingGridSkeleton";

export default async function Home({
  searchParams,
}: {
  searchParams: ListingSearchParams;
}) {
  const beds = searchParams?.bedrooms ?? "0";
  const baths = searchParams?.bathrooms ?? "0";
  const park = searchParams?.parking ?? "0";
  const price = searchParams?.price ?? "0";

  return (
    <main className="flex -h-screen flex-col items-center justify-between p-24">
      <ListingGridFilter />
      <Suspense
        key={beds + baths + park + price}
        fallback={<ListingGridSkeleton />}
      >
        <ListingGrid searchParams={searchParams} /> // <--- Data loading is happening here
      </Suspense>
    </main>
  );
}
// ListingGrid.tsx
// note that this is also a server component

import {
  ListingData,
  ListingSearchParams,
  ListingType,
} from "@/app/lib/listing/data";
import { ListingCard } from "./ListingCard";
import { unstable_noStore } from "next/cache";

export async function ListingGrid({
  searchParams,
}: {
  searchParams: ListingSearchParams;
}) {
   // This is just to force requests to be fetched every time
   // so you can see the components loading.
  unstable_noStore();
  const listing: Array<ListingType> = await ListingData(searchParams);

  if (!listing.length) {
    return <p className="text-xl">No listing matches your criteria</p>;
  }

  return (
    <div className="w-3/4 grid grid-cols-1 2xl:grid-cols-4 xl:grid-cols-3 lg:grid-cols-2 gap-y-12 gap-x-4">
      {listing.map((listingItem) => (
        <ListingCard key={listingItem.Id} listing={listingItem} />
      ))}
    </div>
  );
}

Adding the key in Suspense worked for me, but then turned the entire route dynamic. I was hoping to use partial prerendering, but that only works if I remove they key from Suspense, which then causes the fallback to not trigger lol.

const Page = ({ searchParams }) => {
  return (
    <>
      <Suspense key={JSON.stringify(searchParams)}>
        <DynamicContent searchParams={searchParams} />
      </Suspense>
      <StaticContent />
    </>
  )
}

This works visually as expected, but causes the whole route to be dynamic

Edit: This only worked locally, and did not work when deployed.

Thanks for the response @Fredkiss3 ! I’m sure it will help someone.

Unfortunately for my scenario that won’t trigger the suspense boundary because I am loading new data via the a react server component. I would think the loading.tsx file would hit the fallback since that is the suspense boundary of my page.tsx.

@leerob Could we have any updates regarding this issue?

If the behavior you are looking for is this:

  1. You have a form which updates search params
  2. You want to prefetch and client-side transition to the loading state
  3. The Suspense boundary should be keyed on the search params

Then we now have an example working on canary with next/form (new):

I use startTransition like that.

 const [isPending, startTransition] = useTransition();
    ....
   startTransition(() => {
      router.replace(`${pathname}?${params.toString()}`);
    });

If isPending is true ,I show Loading component. Although this is client side management, this woks.

@Fredkiss3

Thanks for the tweet thread, I hopped in the replies. Since NextJS is handling the boundaries, there should be a way to re-trigger the suspense boundary, whether that’s giving loading.tsx knowledge of the params, or having search params be included in the keys.

I’m not sure what @sebmarkbage means that search params are generally used differently.

If I’m not using them correctly in my bug, I can refactor to use params for my pagination. But having something like app/page/[pageNumber]/page.tsx feels overkill for paging through a table (especially when the result set can vary in length).

edit:

I’ve updated the sandbox to include a refactored version of pagination using [pageNumber].

@dclark27

The key thing seems to be how it is supposed to work : https://twitter.com/sebmarkbage/status/1688622875702345728?s=46

Normally if you want to trigger suspense boundaries, you have to fetch your data in a subcomponent not the page directly, this is fairly easy as you can pass props from the page to another component.

If, like me, you’re tired of this and just need a solution—no matter how it looks—here you go.

const a = document.createElement('a');
a.href = `${pathname}${queryString ? `?${queryString}` : ""}`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();

Creating an invisible link and triggering a click on it worked for me without any additional changes. It even triggered suspense with the loading.tsx file.

I’m confused by the behavior Suspense has on Server components and don’t know how much of it is working as intended. Some people here suggest that there are workarounds, but I haven’t found any for my specific problem. I created https://github.com/nachogutierrez/nextjs-suspense-bug-example to explain what I mean. I use ValueSetter to represent client components that update search params in the URL, and ContentLoader to represent an async server component that fetches data and then renders something (note: to simulate latency, ContentLoader always takes 2 seconds to render). Lastly there’s only one page which renders two value setters for search params ‘A’ and ‘B’, and 1 or 2 content loaders depending on which case it is (see below).

I created branches case-N for N={1,2,3,4,5} to show a few things I found intersting. Each case is defined by how many content loaders (and thus how many Suspense boundaries) there are and what keys are used in each. There are only two possible keys: keyA which is whatever value was set in the ‘A’ search param and similar for keyB. In some cases there are no keys. Here are my findings:

branch Suspense boundaries Keys notes
case-1 1 no key No updates to either keyA or keyB result in the fallback being triggered and search params in the URL are updated after 2 seconds. I guess this is expected because there’s no key set.
case-2 1 keyA Updates to keyA result in the loader’s fallback being triggered, and the search parameter in the URL is updated immediately. Updates to keyB don’t result in fallback being triggered and the search parameter in the URL is updated after 2 seconds. This behavior was expected because keyB is not used in the Suspense boundary.
case-3 2 keyA / keyB No updates to either keyA or keyB result in either fallback being triggered. This is the case I’m most interested in because it reflects what I do in my app (different subset of search params are relevant for different Suspense boundaries). I expected the first loader to trigger its fallback upon changes to keyA and the second loader to trigger its fallback upon changes to keyB. In both cases I expected the updated search params to appear in the URL instantly, but it takes 2 seconds to do so.
case-4 2 keyA / keyA This is REALLY strange behavior, each subsequent update of keyA results in cloned elements in the DOM. The list of content loaders gets bigger and bigger, and the fallback is triggered for the last two loaders. This makes absolutely no sense, so I assume this is a bug.
case-5 2 keyA / keyA The difference here is that the Suspense components are not siblings in the DOM, they have different parent containers. For some reason this fixes the really strange behavior found in case-4. In this case updates to keyA trigger the fallback for the first content loader but not for the second, I was expecting both to trigger their fallback since they have the same key. Updates to keyB don’t trigger any fallback and it takes 2 seconds to see the updated search params in the URL.

@leerob I gave the new Form component in canary a try but I don’t think it solves the problem I have with case-3. I created branch case-3.2 with a different implementation of ValueSetter that uses a Form. Unfortunately the navigation via Form triggers the fallback for all content loaders, not just the one for which the key was updated. Moreover, form submission seems to erase any search param from the URL that isn’t controlled by that Form. This is a problem for me because in my real app I can’t put all client components that update the search params under the same Form, they could be in different parts of the DOM. Is there any workaround for case-3?

This really needs to be addressed, can’t use server-side data fetching for a data-intensive chart now 😦

If anyone else runs into this issue (specifically with PPR), using regular html anchor tags worked for me. You don’t get all the benefits of the Next <Link/>, but it shows the loading fallback until the team can implement client side navigation.

I also heard back from Vercel. Even if it works locally, they say to take it up with Next since it’s an experimental feature. It’s not their problem, according to them (they were nice, I don’t mean to imply they weren’t).

I’ve encountered the same issue. If the API has a cold start when performing a search, I would like to show the “loading” state from loading.tsc file till the current request is finished.

I was having this issue with my app and it was driving me insane, so I created this repo comparing different techniques.

My conclusion was that NextJS already works for this as-is. However, my methodology could be faulty. But if it isn’t faulty, then hopefully this helps people solve this problem.

https://github.com/blisst/nextjs-urlsearchparam-methods

Adding a key to suspense works locally, but NOT hosted on Vercel.

@christopher-caldwell Unfortunately, this is still the case with Next.js 15 Canary and experimental PPR. – Did you ever found a workaround/solution?

cc @leerob

@AChangXD you can just put the data fetching into an async component that you then wrap in Suspense in your page.tsx file. You can then add the fallback to the suspense instead of using loading.tsx and it works. NOTE: if you’re using search params to navigate you do have to put a key on the Suspense that changes, so that it actually triggers the fallback though for example:


  key={`${searchParams.query}${searchParams.otherParam}`}

Yeah I didn’t realize the key needs to be dynamic, working now😃

@AChangXD you can just put the data fetching into an async component that you then wrap in Suspense in your page.tsx file. You can then add the fallback to the suspense instead of using loading.tsx and it works. NOTE: if you’re using search params to navigate you do have to put a key on the Suspense that changes, so that it actually triggers the fallback though for example:

  key={`${searchParams.query}${searchParams.otherParam}`}

Hi all, I tried a workaround and it works for me. Please try to convert your page.tsx to a client component using "use client" , get searchParams by useSearchParams() instead of the page props and wrap the server component that fetch data in <Suspense> as follows. Hope it helps. Thanks. page.tsx

"use client";

import { Suspense } from "react";
import BlogSkeleton from "../../../components/ui/BlogSkeleton";
import AllBlogPosts from "./AllBlogPosts";
import { useSearchParams } from "next/navigation";
import BlogLayout from "../../../components/section/BlogLayout";

const Blog = () => {

  const searchParams = useSearchParams();
  const searchParamsValue = searchParams.has("type")
    ? searchParams.get("type")
    : "all";


  const keyString = searchParamsValue ? searchParamsValue : "all";

  return (
    <BlogLayout>
      <Suspense key={`type=${keyString}`} fallback={<BlogSkeleton />}>
        <AllBlogPosts searchParamsValue={keyString} />
      </Suspense>
    </BlogLayout>
  );
};
export default Blog;

Unfortunately, this solution wastes all the benefits of using server components.

I somewhat agree with you. However, given that my app is kind of light-weighted and it’s acceptable for me to shift the rendering to client side.

@Fredkiss3 did you test it in production too ? because it worked for me in dev mode but in production it didn’t

I use searchParams inside my server component with suspense and useOptimistic in my “use client” component, and everything works as expected.

https://github.com/user-attachments/assets/e98a1107-d055-43c2-9973-ac0a531f7055

I made a short video that demonstrates the suspense being triggered instantly after I click a button that updates the URL searchParams.

You need to use startTransition and useOptimistic from React to optimistically update the UI while the router.push is being appended to the URL. You can also see that only the part of the page that is wrapped in suspense is updating while the static part still works.

Am I missing something?

@leerob can you shed some insight here? https://github.com/vercel/next.js/issues/53543#issuecomment-2626133656 has some valid points.

@csmartinsfct you need to press enter – we could probably change this to be onChange.

Hey @leerob,

first: Wow, what a fast & helpful reply. You’re an absolute OG. 🫶

Using <Form action=…> also for data querying via search params wasn’t something that came to my mind. It’s still kind of an exotic paradigm for me, but nonetheless, I gave it a try.

In my case it’s a simple pagination I want to get to work, I rebuilt the navigation buttons like that (I gave them each their separate <Form> element with a hidden input field – But I’m happy to know if a solution with only one form comes to your mind):

// Get the `page` param (type-safely via nuqs)
const [page] = useQueryState('page', parseAsInteger.withDefault(1))

return (
  <PaginationFormAction page={page} newPage={Math.max(page - 1, 1)}>
    <ChevronLeft className="h-4 w-4" />
  </PaginationFormAction>

  <PaginationFormAction page={page} newPage={Math.min(page + 1, totalPages)}>
    <ChevronRight className="h-4 w-4" />
  </PaginationFormAction>
)
interface PaginationFormActionProps extends HTMLAttributes<HTMLFormElement> {
  page: number
  newPage: number
}
const PaginationFormAction = ({ children, page, newPage }: PaginationFormActionProps) => {
  return (
    <Form action="" replace={true} scroll={false}>
      <input type="hidden" name="page" value={newPage} />
      <Button variant="outline" className="h-8 w-8 p-0" disabled={page === newPage}>
        {children}
      </Button>
    </Form>
  )
}

The asynchronous server components that perform the data fetching are wrapped in a Suspense key-ed with the search params (as suggested above):

<Suspense
  key={JSON.stringify(props.searchParams)} // Note: Using `props.searchParams` here as I pass down `searchParams` into a nested server component and make use of PPR
  fallback={<Skeleton />}
>
  <Items />
  <Pagination />
</Suspense>

And voilà: It work’s as it should. 🎉 But only locally (both via next dev & next build), not on Vercel. 🚨

The live version deployed to Vercel (same node version) just doesn’t show the Suspense fallback at all. The site is frozen/blocked until the fresh data is awaited.

It basically yields to the exact same problem I, and some others above like @christopher-caldwell, have had before just with a different approach (using Form) 😕

Have you tried deploying the commerce example? Is Vercel not yet ready for PPR (even though it’s in experimentation-state for 1 year)?

Are there any fixes in sight? Many threads about this that have been open for 1+ years.

@remitone that should be fine, just wrap that component in suspense where ever youre rendering it, and add they key prop

@ubirajaramneto Thanks for your suggestions. I appreciate you taking a look.

I have implemented them, but didn’t seem to change anything: https://ppr-loading-suspense-demo-git-ubira-e4da36-christopher-caldwell.vercel.app/ and https://github.com/christopher-caldwell/ppr-loading-suspense-demo/blob/ubirajara-suggestions/app/page.tsx

Something to note, your project does not have the ppr experimental flag. I understand that I might be up a creek due to it being experimental, but wanted to point that out.

For the wait, it is just to simulate the network taking longer than expected. It doesn’t wrap the call, wait is a function that is awaited inside the API call function. I removed it anyway just to be sure.

I put in a support ticket with Vercel, as this works when I run it on my computer with yarn start. We shall see what happens.

@ubirajaramneto Adding unstable_noStore did not change the result for me. It works local, but not hosted. Maybe my particular issue is with Vercel, and not Next itself.

With Suspense key: https://ppr-loading-suspense-demo.vercel.app/?page=1 Without Suspense key: https://ppr-loading-suspense-demo.vercel.app/without-suspense-key?page=1

I mostly want to know if this behavior is considered intentional for where the dev team is in the development process of PPR. I understand that features will trickle in, but is this supposed to be happening? At least for now.

Edit: yarn build and then yarn start on my local machine, and this works as expected. I think my issue might be with Vercel in their hosting.

Got the same problem. I tried @Fredkiss3 's solution by passing a key to <Suspense> but it didn’t work, not even in dev stage.

I’ve got the same issue Suspense isn’t being triggered for searchParams at all.

@dclark27 did you find a solution for this problem ?