Search

Server + Client

How to fetch on server and client with SWR

To 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.

Query Pattern

When fetching data using SWR with both Server and Client Components, the following sequence occurs:

BothFetched from the server, while revalidatingAPISingaporeServerSan FranciscoBrowserSan Francisco
StepEnvironmentDescription
PreBrowserSends a request to the server for the website at https://example.com.
1ServerRetrieves the cached response for the relevant API query and returns the rendered HTML containing the cached data.
2BrowserHydrates the page with the cached data and simultaneously initiates a client-side request to fetch the latest data.
3BrowserReceives the fresh data and updates the UI accordingly.
PostServerAfter 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.

GET Request

1. Start with Server Query

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} />
    )
}

2. Revalidate on Client

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