Server and client component composition helps you build fast and interactive web pages by mixing parts that run on the server with parts that run in the browser.
Server and client component composition in NextJS
// Server component file export default function ServerComponent() { return ( <div> <h1>Server Component</h1> <ClientComponent /> </div> ) } // Client component file (separate file) 'use client' import { useState } from 'react' export function ClientComponent() { const [count, setCount] = useState(0) return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ) }
Server components are the default in Next.js 13 App Router.
Client components must start with 'use client' at the top.
import ClientOnly from './ClientOnly' // 'use client' component export default function Page() { return ( <main> <ServerOnly /> <ClientOnly /> </main> ) } function ServerOnly() { return <p>This runs on the server.</p> } // ./ClientOnly.tsx 'use client' import { useState } from 'react' function ClientOnly() { const [text, setText] = useState('') return <input value={text} onChange={e => setText(e.target.value)} /> }
'use client'. It can be used inside a server component.'use client' import { useState } from 'react' export function Counter() { const [count, setCount] = useState(0) return <button onClick={() => setCount(count + 1)}>Count: {count}</button> } export default function Page() { return ( <div> <h1>Server Component</h1> <Counter /> </div> ) }
This example shows a server component HomePage that renders a client component Clicker. The client component handles user clicks and updates the count.
It uses semantic HTML and an ARIA label for accessibility.
import Clicker from './Clicker' // 'use client' component export default function HomePage() { return ( <main> <h1>Welcome to the Server Component</h1> <Clicker /> </main> ) } // ./Clicker.tsx 'use client' import { useState } from 'react' export default function Clicker() { const [clicks, setClicks] = useState(0) return ( <button onClick={() => setClicks(clicks + 1)} aria-label="Click counter button"> Clicked {clicks} times </button> ) }
Always put 'use client' at the very top of client components.
Server components cannot use React hooks like useState or useEffect.
Client components can be nested inside server components to add interactivity.
Server components render on the server and are fast and secure.
Client components run in the browser and handle user interaction.
Use composition to combine server and client components for best performance and interactivity.