Bilal Gokdag
Blog'a Dön

React Server Components Guide

A deep dive into React Server Components (RSC) and how they change the way we build React applications.

React Server Components Guide

React Server Components (RSC) represent a paradigm shift in how we build React applications. They allow us to render components on the server, reducing the amount of JavaScript sent to the client.

What are Server Components?

By default, in the Next.js App Router, all components are Server Components. They execute on the server and send HTML to the client. This means they can directly access your database or file system without needing an API route.

// This runs on the server
import db from '@/lib/db'

export default async function UserList() {
  const users = await db.query('SELECT * FROM users')
  
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

When to use Client Components?

You only need to use Client Components when you need interactivity or browser APIs. You declare them with the 'use client' directive.

'use client'

import { useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0)
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  )
}

The Composition Pattern

The most powerful pattern is passing Server Components as children to Client Components. This allows you to have interactive wrappers around static server-rendered content.

// ClientWrapper.tsx
'use client'
export default function ClientWrapper({ children }) {
  return <div className="interactive-wrapper">{children}</div>
}

// Page.tsx
import ClientWrapper from './ClientWrapper'
import ServerData from './ServerData'

export default function Page() {
  return (
    <ClientWrapper>
      <ServerData />
    </ClientWrapper>
  )
}

Conclusion

RSC is a game-changer for performance and developer experience. Embrace the server-first approach and only use client components when absolutely necessary.