Solution
The page component is server side. So if we can import the server component and pass it as a child prop to client component. In this way server and client components are decoupled and it will solve our issue. Place the children where you want to data to be placed. Behind the scene, Next.js is rendering the server component before the rendering of client component.
//components/ClientComp.tsx
"use client"
import { useState } from "react"
const ClientComp: React.FC
< { children: React.ReactNode } > = ({ children }) => {
const [state, setState] = useState(0)
return (
<div className="w-full h-screen flex
justify-center items-center">
<div className="w-2/3 h-2/3 bg-pink-300
flex flex-col justify-center items-center">
<p className="text-3xl font-semibold">Client Component</p>
<p className="mb-5">Rendered on Client side</p>
<div className="flex gap-3 border border-black
rounded-lg p-2 px-5 m-2">
<p className="text-2xl font-semibold">
Count: {state}</p>
<button className="bg-blue-500 hover:bg-blue-700
text-white font-bold py-2 px-4 rounded"
onClick={() => setState(state + 1)}
>
Click
</button>
</div>
{children}
</div>
</div>
)
}
export default ClientComp
//app/page.tsx
import ClientComp from '@/components/ClientComp'
import ServerComp from '@/components/ServerComp'
import React from 'react'
const page = () => {
return (
<ClientComp>
<ServerComp />
</ClientComp>
)
}
export default page
Now we are passing server component from page component which is a server component to client component. If you see now see source tab in developer tools, server component will not show and console logs are now appearing as the it is rendering on server side.
Proper way to use server component inside a client component in Next.js
Next.js, a popular React framework, helps to build powerful web applications with ease. One of its standout features is the ability to seamlessly integrate server-side logic alongside client-side components. This allows for dynamic content rendering, efficient data fetching, and enhanced user experiences. In this article, we’ll explore how to use server-side components within client-side components in Next.js applications.