use client
use client
ディレクティブは、コンポーネントをクライアント側でレンダリングするよう指定し、状態管理、イベントハンドリング、ブラウザAPIへのアクセスなど、クライアント側のJavaScript機能を必要とするインタラクティブなユーザーインターフェース(UI)を作成する際に使用されます。これはReactの機能です。
使用方法
コンポーネントをClient Componentとして指定するには、任意のインポートの前に、ファイルの先頭に use client
ディレクティブを追加します:
app/components/counter.tsx
TypeScript
'use client'
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}
Server Componentの中にClient Componentを入れ子にする
Server ComponentとClient Componentを組み合わせることで、パフォーマンスと対話性の両方を備えたアプリケーションを構築できます:
- Server Components:静的コンテンツ、データフェッチ、SEOに優しい要素に使用します。
- Client Components:状態、エフェクト、またはブラウザAPIを必要とするインタラクティブな要素に使用します。
- コンポーネントの構成:必要に応じてServer ComponentにClient Componentを入れ子にし、サーバーとクライアントのロジックを明確に分離します。
次の例では:
Header
は静的コンテンツを処理するServer Componentです。Counter
はページ内のインタラクティブ性を可能にするClient Componentです。
app/page.tsx
TypeScript
import Header from './header'
import Counter from './counter' // これはClient Componentです
export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}
リファレンス
use client
の詳細については、React ドキュメントを参照してください。