Client-Side Rendering (CSR)

This section explains the principles and benefits of client-side rendering in web applications.

When to use CSR?

Client-side rendering (CSR) is particularly useful when you want to achieve the following:

  • Dynamic Interactivity: CSR allows for highly interactive applications where users can interact with the UI without requiring full page reloads. This is ideal for applications with complex user interfaces, such as single-page applications (SPAs).
  • Rich User Experience: CSR enables a more fluid and responsive user experience, as it allows for real-time updates and interactions without the need to fetch new HTML from the server for every action.
  • Reduced Server Load: By offloading rendering to the client, CSR can reduce the load on the server, as the server only needs to provide the initial HTML and subsequent data requests, rather than full page renders.
  • Asynchronous Data Fetching: CSR allows for fetching data asynchronously, which means that the application can load data in the background while the user interacts with the page. This can lead to a more seamless experience, as users can continue to interact with the application while data is being fetched.
  • Improved Performance for Certain Use Cases: CSR can improve performance for applications that require frequent updates or interactions, as it minimizes the need for full page reloads and allows for faster updates to the UI.

How to implement CSR in Next.js with Apollo Client

To implement client-side rendering (CSR) in a Next.js application using Apollo Client, you need to follow these steps:

  1. use client directive: Ensure that your component is marked as a client component by adding the "use client" directive at the top of your file. This tells Next.js to render this component on the client side.
// app/components/your-component.tsx
"use client";
import { useEffect, useState } from "react";
import { GET_CMS_POSTS } from "@/graphql/queries";
import { CmsPosts } from "@/types/cms";
import { useQuery } from "@apollo/client";

export default function Page() {
  const [posts, setPosts] = useState<CmsPosts[]>([]);

  const { data, loading, error } = useQuery(GET_CMS_POSTS, {
    variables: { clientPortalId: "your-client-portal-id", categoryId: "your-category-id", page: 1, perPage: 10, language: "en" },
  });

  useEffect(() => {
    if (data) {
      setPosts(data.cmsPosts);
    }
  }, [data]);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Client-Side Rendered Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}