#ServerComponents rendered as ClientComponents

1 messages · Page 1 of 1 (latest)

carmine epoch
#

Hello, I am in the NextJS 14 App router.
If i have a page.tsx that is a 'use client'
and inside it i am rendering several components

// src/app/account/page.tsx
`
'use client'
import React from 'react'
import ServerComponent from '../../components/ServerComponent.tsx'

function page() {
return (
<>
<ClientComponent />
<ServerComponent />
</>
)
}

export default page
`
Will this make the <ServerComponent /> a client-component ?

cosmic fableBOT
#

Hi @carmine epoch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, in the scenario you've described, the ServerComponent will not behave as a typical server component. This is because you're trying to import a Server Component into a Client Component, which is an unsupported pattern in Next.js.

In Next.js, when you declare a file with 'use client', it means that the file and all its imports are expected to run on the client-side. Therefore, importing a Server Component into a Client Component would require a new request back to the server, which is not supported.

However, there is a supported pattern where you can pass Server Components as a prop to a Client Component. This is often done using the React children prop to create a "slot" in your Client Component. Here's an example:

// Client Component
'use client'
import { useState } from 'react'
 
export default function ClientComponent({
 children,
}: {
 children: React.ReactNode
}) {
 const [count, setCount] = useState(0)
 
 return (
 <>
 <button onClick={() => setCount(count + 1)}>{count}</button>
 {children}
 </>
 )
}

// Parent Server Component
import ClientComponent from './client-component'
import ServerComponent from './server-component'
 
// Pages in Next.js are Server Components by default
export default function Page() {
 return (
 <ClientComponent>
 <ServerComponent />
 </ClientComponent>
 )
}

In this case, the ServerComponent is passed as a child of ClientComponent, and they are decoupled and can be rendered independently. The ServerComponent can be rendered on the server, well before ClientComponent is rendered on the client.