vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.62k stars 26.82k forks source link

Next.js App Router: Server Component with Context Provider and Tailwind causes rendering issues #69682

Open jmderby opened 1 month ago

jmderby commented 1 month ago

Link to the code that reproduces this issue

https://github.com/jmderby/min-repro-next-render-issue

To Reproduce

  1. run pnpm i
  2. run pnpm dev
  3. visit localhost:3000, see console logs not display on the client browser console. Caveat: Issue will reproduce intermittently, to repro successfully, restart the Next.js server.

Current vs. Expected behavior

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000
  Available memory (MB): 16384
  Available CPU cores: 8
Binaries:
  Node: 20.16.0
  npm: 10.8.1
  Yarn: N/A
  pnpm: 9.7.1
Relevant Packages:
  next: 14.2.7 // Latest available version is detected (14.2.7).
  eslint-config-next: 14.2.7
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.5.4
  tailwindcss: 3.4.1,
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

create-next-app, Developer Experience, Runtime

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

This issue seems to be related to the interaction between Server Components, Client Components with Context Providers, and importing globals.css which contains the Tailwind directives from the layout.tsx Server Component. It persists even when following Next.js best practices for mixing Server, Client Components, and Context Providers.

The issue is most noticeable immediately after starting the development server. If you refresh the page after the initial load, the app typically functions as expected. The problem primarily affects the first render following server startup.

A minimal reproduction repository has been created to demonstrate this issue.

This minimal reproduction was inspired by this Vercel guide of using React Context with Next.js: https://vercel.com/guides/react-context-state-management-nextjs

chidaihuashi commented 2 weeks ago

I am using 'use client' and this issue does not arise

` export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { 'use client'

return (
    <html lang="en" className={HarmonyOS.className}>
        <body className={styles.appContainer}>
            <Header></Header>
            <ReduxProvider>
                <AntdRegistry>{children}</AntdRegistry>
            </ReduxProvider>
        </body>
    </html>
)

} `

AlbertoElias commented 2 weeks ago

I would rather not depend on 'use client'; in a layout component for performance and SEO reasons. Ideally, it would be rendered server-side