![]() |
VOOZH | about |
Caching is all about storing copies of the data in temporary storage, and that stored data is called cache. The main reason to do caching is that, in the future, when that data is needed, it can be served faster, and we don't have to fetch the data from the original source, because that can take some extra time, which can cause a performance issue, if the fetching process is done quite frequently.
Next.js, a popular React framework, offers several caching strategies that developers can use to optimize their applications.
Step 1: Create a React application using the following command:
npx create-next-app@latest testappStep 2: After creating your project folder i.e. testapp, move to it using the following command:
cd testappStep 3: After creating the nextJS app we have to create an another directory testpage inside that create a file page.tsx, after all that this is what our project directory will look like.
"dependencies":
{
"react": "^18",
"react-dom": "^18",
"next": "14.2.3"
}
Static Generation is a method where HTML pages are pre-rendered at build time. This results in faster load times since the content is served as static files. Pages generated this way can also be cached on the CDN level. Incremental Static Regeneration (ISR) allows you to update static content after the site has been built and deployed. With ISR, you can regenerate specific pages based on a predefined interval or trigger, ensuring the content remains fresh without rebuilding the entire site.
Example: By using the revalidate option, Next.js allows you to cache statically generated pages on the server.
export async function getStaticProps() {
const data = await fetchData();
return {
props: {
data,
},
revalidate: 10, // Regenerate the page every 10 seconds
};
}
In this example, the page will be revalidated and regenerated every 10 seconds, ensuring fresh content while maintaining the performance benefits of static generation.
Server-Side Rendering generates HTML pages on each request. While SSR ensures that content is always up-to-date, it can be slower compared to SSG. To improve performance, caching strategies can be implemented to store rendered HTML and reuse it for subsequent requests.
Example: Using HTTP headers, you can instruct the browser to cache server-rendered pages. Here, Cache-Control header specifies that the response can be cached by any cache (public), should be revalidated after 10 seconds (s-maxage=10), and can be served stale while revalidating for up to 59 seconds.
export async function getServerSideProps(context) {
const res = await fetch(`https://...`);
const data = await res.json();
context.res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
);
return { props: { data } };
}
API routes in Next.js can benefit from caching to reduce latency and server load. Implementing caching in API routes ensures that frequently accessed data is served quickly.
Example: Using a caching library, you can cache API responses in Next.js.
import { NextApiRequest, NextApiResponse } from 'next';
import { cache } from 'some-cache-library';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const cachedData = cache.get(req.url);
if (cachedData) {
res.status(200).json(cachedData);
return;
}
const data = await fetchData();
cache.set(req.url, data, 60); // Cache for 60 seconds
res.status(200).json(data);
}
Client-side caching involves storing data in the browser to reduce the need for repeated network requests. This can be achieved using service workers, local storage, or in-memory caching.
Example: Using the react-query library, you can cache API responses in memory.
import { useQuery } from 'react-query';
function MyComponent() {
const { data, error, isLoading } = useQuery('fetchData', fetchData, {
staleTime: 30000, // Cache data for 30 seconds
});
// Render component
}
Example : In Next.js, server-side rendered pages are automatically cached, retaining state between navigations, while client-side rendered pages do not inherently cache state, resulting in potential data changes with each navigation.
Output