久しぶりに触るNext.js: Client ComponentsでServer Actionsを使う
The Road to Next.jsを受講して、Client ComponentsでServer Actionsを活用する方法を学びました。今回は、その経験を元に、具体例を交えてServer Actionsの使い方を解説します。Server Actionsはクライアントサイドのパフォーマンスを向上させ、コードをシンプルに保つための強力なツールです。この記事では、Client Componentsとの組み合わせでその可能性を探っていきます。
Server Actionsとは?
Server Actionsは、サーバーサイドのロジックをReactコンポーネントの一部として直接記述できるものです。これにより以下のメリットがあります:
- APIルートが不要:APIエンドポイントを別途作成する必要がなく、ロジックをシンプルに記述可能。
- クライアントサイドの負荷軽減:データ処理をサーバーで実行し、クライアントのパフォーマンスを向上。
- 宣言的で明快なコード:フロントエンドとバックエンドの境界が曖昧になり、実装が容易になる。
Client ComponentsでServer Actionsを使う
以下では、Server Actionsを使ってサーバーでデータを取得し、それをClient Componentに反映させる例を示します。
Server Actionsの定義
Server Actionは、サーバーサイドで実行されるロジックを含む関数として定義されます。以下は、ユーザーデータをAPIから取得するServer Actionの例です。
// app/actions.tsx
"use server";
export async function getUserData(userId) {
const response = await fetch(`https://api.example.com/user/${userId}`);
if (!response.ok) {
throw new Error("Failed to fetch user data");
}
return response.json();
}
Server Actionを定義するには、"use server"ディレクティブを先頭に追加します。これにより、この関数がサーバー上で実行されることをNext.jsに伝えます。
Client Componentsでの使用例
Client Componentでは、Server Actionを直接呼び出すことができます。以下は、ユーザーのプロフィール情報を取得して表示する例です。
// app/components/UserProfile.js
"use client";
import { useState } from "react";
import { getUserData } from "../actions";
export default function UserProfile() {
const [userData, setUserData] = useState(null);
const [error, setError] = useState(null);
async function handleFetchUser() {
try {
const data = await getUserData(123); // ユーザーIDを指定
setUserData(data);
} catch (err) {
setError("ユーザーデータの取得に失敗しました");
}
}
return (
<div>
<h1>User Profile</h1>
<button onClick={handleFetchUser}>Fetch User Data</button>
{error && <p style={{ color: "red" }}>{error}</p>}
{userData && (
<div>
<p>Name: {userData.name}</p>
<p>Email: {userData.email}</p>
</div>
)}
</div>
);
}
この例では、ボタンをクリックすると、getUserDataがサーバーで実行され、取得したデータがクライアントコンポーネントに表示されます。
注意点
- 型安全性の確保
TypeScriptを活用して、Server Actionの入力と出力の型を明確に定義することで、予期せぬエラーを防ぎます。 - エラーハンドリング
APIが失敗した場合のエラーメッセージやリトライロジックを実装して、ユーザー体験を向上させます。 - パフォーマンスの最適化
頻繁にデータを取得する場合は、キャッシュ戦略を検討し、無駄な通信を減らします。
まとめ
Next.jsのClient ComponentsでServer Actionsを活用することで、より直感的でシンプルなコードが書けるようになります。APIルートやfetchを別途設定する必要がなく、クライアントとサーバーの境界を意識せずに開発を進められるのは大きな利点です。
Discussion