Documentation
Getting Started
Functions
Guides
Concepts
Server + Client
How to fetch on server and client with SWRTo fetch data using SWR (Stale-While-Revalidate) while leveraging both Server and Client Components, you can combine the serverQuery
and clientQuery
functions.
This pattern is ideal when you want to show cached data immediately on page load, then seamlessly update it with fresh data on the client.
Since the data is fetched on the server, it's included in the initial page load, significantly improving perceived performance.
When fetching data using SWR with both Server and Client Components, the following sequence occurs:
Step | Environment | Description |
---|---|---|
Pre | Browser | Sends a request to the server for the website at https://example.com . |
1 | Server | Retrieves the cached response for the relevant API query and returns the rendered HTML containing the cached data. |
2 | Browser | Hydrates the page with the cached data and simultaneously initiates a client-side request to fetch the latest data. |
3 | Browser | Receives the fresh data and updates the UI accordingly. |
Post | Server | After sending the response, server checks if the cached data is stale. If it is, it fetches fresh data from the API to update the cache for future requests. |
The following example fetches data on the server using a GET request.
The returned data is then passed as initial data to the ClientComponent
.
import { serverQuery } from "@bigbang-sdk/next-query";
async function ServerComponent() {
const { data, error } = await serverQuery({
queryUrl: "https://api.example.com/data",
});
return (
<ClientComponent initialData={data} />
)
}
The following example receives initialData
as props from the ServerComponent
and then fetches fresh data on the client using clientQuery
.
"use client";
import { useState, useEffect } from "react";
import { clientQuery } from "@bigbang-sdk/next-query";
function ClientComponent({ initialData }: { initialData: any }) {
const [fetchedData, setFetchedData] = useState(initialData);
const { data, error, isLoading } = clientQuery({
queryUrl: "https://api.example.com/data"
});
useEffect(() => {
setFetchedData(data);
}, [data]);
return (
<div>
<p>{fetchedData}</p>
</div>
)
}
Made with
by Bigbang