ProNextJS

    What's The Order Of Component Rendering?

    Jack HerringtonJack Herrington

    Q: What's the order of component rendering?

    A: This is a fun one because components don't render in the order that you think they do when you are using the NextJS App Router. RSCs render in a reliable order, but if you have a mix of client components and server components (which is likely) then that will alter the ordering.

    Let's say you have three components; ComponentA, ComponentB, and ComponentC all of which look like this:

    const ComponentA = ({ children }: { children?: React.ReactNode }) => {
      console.log("Component A");
      return (
        <div>
          <h1>Component A</h1>
          {children}
        </div>
      );
    };
    

    And your page is structured to have them one after the other:

    export default function Home() {
      return (
        <main>
          <ComponentA />
          <ComponentB />
          <ComponentC />
        </main>
      );
    

    Then they will render in A, B, C order. Now let's switch them up using "transclusion", which means using children for containment, like this:

    export default function Home() {
      return (
        <main>
          <ComponentC>
            <ComponentB>
              <ComponentA />
            </ComponentB>
          </ComponentC>
        </main>
      );
    }
    

    So C contains B and B contains A. Now the rendering will go C, B, A and it depends on the order of containment.

    However that's not really the whole story, if you change ComponentB to ClientComponentB and you make it a client component using "use client";. Then you have the Page implemented the same way:

    export default function Home() {
      return (
        <main>
          <ComponentC>
            <ClientComponentB>
              <ComponentA />
            </ClientComponentB>
          </ComponentC>
        </main>
      );
    }
    

    Then the ordering will go C. Then A! Which is pretty interesting, so it renders the RSCs first. Then it will render the client component B.

    One thing is for certain, you should not architect around the specific mechanics of component rendering. They are surprising. And if you make a change like turning an RSC into a client component, then the rendering order can unexpectedly change.

    Subscribe for Free Tips, Tutorials, and Special Discounts

    We're in this together!

    I respect your privacy. Unsubscribe at any time.