Next.js Discord

Discord Forum

Suspense and key weird behavior (Make loading work wrongly)

Unanswered
Pteromalid wasp posted this in #help-forum
Open in Discord
Pteromalid waspOP
I observed a weird behavior in using suspense and key (or I misunderstood the loading behind the scene), [Here is to preview in codesandbox feel free to fork and run
](https://codesandbox.io/p/devbox/brave-sanne-f8z3gh)
import { Suspense } from "react";
import MyButton from "./my-button";

async function ContainerOne() {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  return <div>Container 1</div>
}

async function ContainerTwo() {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return <div>Container 2</div>
}

export default function Home() {
  return (
    <div>
      <Suspense key={Math.random()} fallback={<div>loading 1 ...</div>}>
        <ContainerOne />
      </Suspense>
      {/* <Suspense key={''} fallback={<div>loading 2 ...</div>}> */}
      <Suspense key={Math.random()} fallback={<div>loading 2 ...</div>}>
        <ContainerTwo />
      </Suspense>
      <MyButton />
    </div>
  );
}


if the key are both unique and random (or has changed), both components will behave normally with a loading fallback showing. However, if I changed the "ContainerTwo" key to a constant, let's say key={'b'}, the loading will become this -

"ContainerOne" wait "ContainerTwo" for 1s
"ContainerTwo" no loading (which is expected, since the key doesn't changed)
"ContainerOne" turn into loading for 2s

My expected behavior would be -
"ContainerOne" directly turn into loading for 3s
"ContainerTwo" no loading but data changed after 1s directly

0 Replies