
Next.js は、サーバー側レンダリング (SSR)、静的サイト生成 (SSG)、クライアント側データ取得など、アプリケーションでデータを取得するための強力な機能を提供します。これらのテクニックを活用することで、シームレスなユーザー エクスペリエンスを提供する、パフォーマンスが高くスケーラブルなアプリケーションを構築できます。このガイドでは、Next.js の高度なデータ取得テクニックを探索し、それらをプロジェクトに実装する方法を示します。
// pages/post/[id].js
export async function getServerSideProps(context) {
const { params } = context;
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return {
props: {
post,
},
};
}
const PostPage = ({ post }) => {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
};
export default PostPage;
Next.js での静的サイト生成により、ビルド時にページを事前レンダリングできるため、コンテンツが静的であり、CDN から直接提供できることが保証されます。これにより、パフォーマンスが大幅に向上し、サーバーの負荷が軽減されます。
// pages/index.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return {
props: {
posts,
},
};
}
const HomePage = ({ posts }) => {
return (
<div>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default HomePage;
Next.js の増分静的再生成により、サイト全体を再構築せずに静的コンテンツを更新できます。これは、ニュース記事やブログ投稿など、頻繁に更新する必要があるページに役立ちます。
// pages/posts/[id].js
export async function getStaticProps(context) {
const { params } = context;
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return {
props: {
post,
},
revalidate: 60, // Revalidate the page every 60 seconds
};
}
const PostPage = ({ post }) => {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
};
export default PostPage;
Next.js はクライアント側のデータ フェッチもサポートしており、最初のページ読み込み後にデータをフェッチできます。これは、最初のレンダリングに必要のないデータを取得したり、データの読み込みが必要なユーザー操作を処理したりする場合に役立ちます。
import { useEffect, useState } from 'react';
const PostsPage = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPosts = async () => {
const res = await fetch('https://api.example.com/posts');
const data = await res.json();
setPosts(data);
setLoading(false);
};
fetchPosts();
}, []);
if (loading) {
return <p>Loading...</p>;
}
return (
<div>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default PostsPage;
多くのアプリケーションでは、パフォーマンスとユーザー エクスペリエンスを最適化するために、さまざまなデータ取得方法を組み合わせる必要がある場合があります。たとえば、最初のページ読み込みには SSR または SSG を使用し、追加データやユーザー インタラクションにはクライアント側でのフェッチを使用できます。
// pages/user/[id].js
import { useEffect, useState } from 'react';
export async function getServerSideProps(context) {
const { params } = context;
const res = await fetch(`https://api.example.com/users/${params.id}`);
const user = await res.json();
return {
props: {
user,
},
};
}
const UserPage = ({ user }) => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPosts = async () => {
const res = await fetch(`https://api.example.com/users/${user.id}/posts`);
const data = await res.json();
setPosts(data);
setLoading(false);
};
fetchPosts();
}, [user.id]);
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
<h2>Posts</h2>
{loading ? (
<p>Loading...</p>
) : (
<div>
{posts.map((post) => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
)}
</div>
);
};
export default UserPage;
SWR (stale-while-revalidate) は、データフェッチ用に Vercel によって作成された React フック ライブラリです。キャッシュ、再検証、フォーカス追跡などの機能を提供し、クライアント側のデータ取得をより効率的かつ強力にします。
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((res) => res.json());
const SWRPostsPage = () => {
const { data, error } = useSWR('https://api.example.com/posts', fetcher);
if (error) return <p>Error loading posts.</p>;
if (!data) return <p>Loading...</p>;
return (
<div>
{data.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default SWRPostsPage;
Next.js は、さまざまなユースケースやパフォーマンス要件に対応するさまざまなデータ取得手法を提供します。 SSR、SSG、ISR、およびクライアント側のデータ取得を理解して活用することで、優れたユーザー エクスペリエンスを提供する強力で高性能な Web アプリケーションを構築できます。これらのテクニックを効果的に組み合わせることで、速度と SEO の両方に関して Next.js アプリケーションを最適化し、ユーザーに可能な限り最高のエクスペリエンスを提供することができます。
以上がNext.js の高度なデータ取得テクニックの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。