In Next.js, you can use the useSWR
hook from the SWR library (Stale-While-Revalidate) for data caching and revalidation. This hook helps in fetching data, caching it locally (in-memory), and automatically revalidating it in the background when the data is stale. Here's how you can use it:
Install SWR: First, you need to install the SWR library in your Next.js project. You can do this using npm or yarn.
bashnpm install swr
or
bashyarn add swr
Import useSWR
: Import the useSWR
hook in your Next.js component where you want to fetch and cache data.
javascriptimport useSWR from 'swr';
Usage: You can use the useSWR
hook by providing it with a key (unique identifier for the data) and a function to fetch the data.
javascriptconst fetcher = (url) => fetch(url).then((res) => res.json());
const MyComponent = () => {
const { data, error } = useSWR('/api/data', fetcher);
if (error) return <div>Error fetching data</div>;
if (!data) return <div>Loading...</div>;
return <div>Data: {data}</div>;
};
export default MyComponent;
Options: useSWR
also accepts an optional third argument for options, where you can specify things like initial data, revalidation intervals, error retry intervals, etc.
javascriptconst { data, error } = useSWR('/api/data', fetcher, {
refreshInterval: 5000, // Revalidate every 5 seconds
});
Automatic Revalidation: By default, SWR will automatically revalidate the data in the background when the component is re-rendered after a certain interval (specified by refreshInterval
) or when the component is re-mounted.
Manual Revalidation: You can also manually trigger a revalidation by calling the mutate
function returned by useSWR
.
javascriptconst { data, error, mutate } = useSWR('/api/data', fetcher);
const refreshData = () => {
mutate();
};
return (
<div>
<button onClick={refreshData}>Refresh Data</button>
<div>Data: {data}</div>
</div>
);
Server-Side Rendering (SSR): If you're using Next.js with server-side rendering, useSWR
will automatically disable caching on the server to ensure each request gets fresh data.
That's it! You've now integrated useSWR
for data caching and revalidation in your Next.js application.