Data caching is like keeping important notes handy for quick reference, speeding up software performance by storing and reusing frequently accessed data, crucial in Next.js for faster page loading and a smoother user experience.
If you’re familiar with the features of Next.js 14, you’ve likely encountered the term caching. In this blog, we’ll explore the best practices for fetching and caching data on the server side.
Data caching is like keeping important notes handy for quick reference, speeding up software performance by storing and reusing frequently accessed data, crucial in Next.js for faster page loading and a smoother user experience.
Route handlers and pages within the app directory of a Next.js app, named page.tsx are inherently server components by default. These components are built upon the same foundation.
Previously, in the pages directory for server-side data fetching, methods like getStaticProps and getServerSideProps were commonly used. However, in the new version, the approach remains quite similar, emphasizing ease of use and familiarity for developers.
Here’s a quick example to demonstrate: consider a simple page created within app/page.tsx Since it’s a server component, data can be fetched like this:
1export default async function Home() {2const res = await fetch("/api/get-post");3const data = await res.json();45return (6<main className="p-24">7<h1>NEXT.js 14</h1>8{data?.posts?.map((post: any) => (9<p key={post.id}>{post.title}</p>10))}11</main>12);13}
In the fetch function, there’s an optional argument called cache, where force-cache is the default value in server components.
1// 'force-cache' is the default, and can be omitted2fetch('https://...', { cache: 'force-cache' })3To avoid caching data, we can set it as follows:45fetch(`https://...`, { cache: 'no-store' })
Adding no-store ensures that new data is fetched with each reload.
Revalidating is akin to the previous Incremental Site Generation feature. By setting a time in seconds, it retains cache for a specific duration, refreshing data upon page refresh. This functionality is valuable for managing dynamic data scenarios.
1// Revalidate at most every hour2fetch('https://...', { next: { revalidate: 3600 } })
When utilizing route handlers as an API, remember that GET requests result in indefinite data caching, making revalidation inapplicable. For scenarios requiring revalidation, opt for POST requests instead of GET.
In summary, this blog has discussed how data caching in Next.js improves performance and user experience. It covered default caching in server components and the importance of revalidation in different request methods. By using these techniques effectively, developers can achieve faster page loading and a smoother user experience.
Join the newsletter
Subscribe for weekly updates. No spams ever!
Copyright © 2024 | Hardik Desai | All Rights Reserved