Comparing Passing Props with Extracting Cache in Apollo Client for Next.js applications

Hello there! I am diving into the world of apollo and graphql, specifically interested in SSR/SSG. While I have a basic understanding of what SSR/SSG entails, implementing it with apollo-client is a bit tricky for me.

After some extensive searching online, I found conflicting information on the correct approach to take. My aim with this post is to clarify the upsides/downsides of two different methods:

// Method 1
const client = new ApolloClient({
  link: new HttpLink({ uri: '/graphql' }),
  cache: new InMemoryCache(),
});

// Component code using getServerSideProps

// Method 2
const createClient = () => new ApolloClient({
  link: new HttpLink({ uri: '/graphql' }),
  cache: new InMemoryCache(),
  ssrMode: typeof window === 'undefined',
});

// Component code using custom hook useApollo

My confusion lies in whether the second method (with SSR) involves unnecessary repetition of queries and extra coding compared to the first method. What are the performance benefits and safety implications of each?

Thank you for your insights!

Answer №1

Your initial approach aligns more closely with the goals of Next. It aims to fetch data at build time for pages using getStaticProps (SSG) or getServerSideProps (SSR), generating pages on the server statically whenever possible.

Referencing Apollo Client in the getStaticProps/getServerSideProps call is not necessary. Context could suffice based on your current code implementation, eliminating the need for Apollo Client.

Personally, I utilize Apollo in Next applications when I need to fetch data into components. While Next lacks a direct solution for this, it's an area where Apollo excels. For example, maintaining a menu that appears across all pages without triggering a full site rebuild if a menu item changes. Apollo ensures all pages remain up-to-date without requiring Next to re-render unnecessarily.

You can find more details on my approach outlined in this answer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

Can we guarantee the uniqueness of a function parameter value during compilation?

I have a set of static identifiers that I want to use to tag function calls. Instead of simply passing the identifiers as arguments, I would like to ensure that each identifier is unique and throws an error if the same identifier is passed more than once: ...

The Angular build is unsuccessful due to the presence of components from a separate Angular project

Whenever I execute ng build project1 --prod, the build fails and displays this error message: ERROR in : Cannot determine the module for class MyComponent in .../project2/app/my.component.ts! Add MyComponent to the NgModule to fix it.. Although the sol ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

Should beginner node.js developers start with NestJs or should they gain experience with Express first?

After completing a project using the Express JS library on the Mozilla (MDN) training site, I started looking for a more reliable option due to various reasons such as architectural concerns and issues with modern JavaScript features like async-await. That ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

Using Typescript for AngularJS bindings with ng.IComponentController

Currently, I am utilizing webpack alongside Babel and Typescript Presently, the controller in question is as follows: // HelloWorldController.ts class HelloWorldController implements ng.IComponentController { constructor(private $scope: ng.IScope) { } ...

Synchronize Docker volumes

Hey there! I've been trying to dive into learning Docker, but I'm having trouble syncing the host and container using volumes when making changes and saving code (specifically using npm run dev). Every time I need to restart docker-compose up --b ...

How can I implement a Component to show the details of a blog post when clicked in Next.js?

Can someone help me figure out how to display individual blog post details in a modal when clicked on in a blog website, where the posts are stored in a Component rather than pages? The file structure is set up like this: Component |_ Posts.js |_ PostDet ...

I'm struggling to make basic CSS work in my Next.js 13 project. I'm a beginner, can someone please help?

I am facing issues with the default CSS in my latest project. I have a file called page.modules.css and I am using classname = styles.style page.tsx import styles from'./page.module.css' export default function Home() { return ( <div cl ...

Conceal components using routing in Angular2 release candidate 1

I have a request regarding certain elements that are to be displayed on all pages except the login page. I am considering using either ngIf or the hidden property of the elements to hide them when the user is on the login page. Here is what I have attempt ...

Receiving a ModuleParseError when attempting to import an SCSS file in Nextjs 13

I am working with Next.js v13 in a monorepo structure. I am facing an issue when attempting to import a scss file within another scss file, resulting in the following error: ModuleParseError: Module parse failed: Unexpected character '@' (1:0) Yo ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

How can I implement the useState hook in server side rendering with Next.js?

Seeking a way to pass a value from the client side to the server side has been challenging. While useState is not available for use on the server side, there must be an alternative solution. The goal is to fetch a value from the client and incorporate it ...

Discovering the specific value within an array of various objects through Angular

Within a list of objects, I am specifically looking to extract the name "sample 4" from the second set of objects with an ID of 2. How can this value be retrieved using JavaScript or Angular? {Id: 1, name: sample 1, code: "type", order: 1} {Id: 1, name: ...

The useEffect function continues to fire twice even when the dependency array is empty

I found a helpful example at https://github.com/vercel/next.js/blob/canary/examples/with-firebase-authentication/utils/auth/useUser.js Although the effect is working fine and firing once, the functions inside are being called twice for some reason. us ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

Successful login callback in Auth.js using next-auth

After a successful login using OAUTH, Magic Link, or Credentials with auth.js (next-auth), is there a specific callback that can be utilized for logging login activities and keeping track of history? Appreciate any help! ...