Apollo Client's useQuery function is causing unnecessary refetches when using Next.js' router.push method

Currently, I'm facing an issue where a query within a useQuery Apollo Client hook is being re-run unnecessarily every time Next.js's router.push function is triggered. The problem code snippet looks like this:

const Parent = () => {
  useQuery(QUERY_HERE, {
    onCompleted: () => {
      console.log("just completed apollo query");
    }
  });

  return <Child />;
}

const Child = () => {
  const router = useRouter();
  const currentArg = router.query?.currentArg;

  return (
    <div>
      <button
        onClick={() => {
          if (currentArg === "on") {
            router.push("/?currentArg=off");
          } else {
            router.push("/?currentArg=on");
          }
        }}
      >
        Click me!
      </button>
    </div>
  );
};

For a live demo, check out CodeSandbox here.

I expected that the Apollo query should not be re-executed whenever the button triggers router.push. However, it seems to run every time the button is clicked. This behavior is unexpected as I believed that an Apollo query would only re-run when its variables change.

Does anyone have any insights or solutions on how to prevent the unnecessary re-running of the Apollo query?

Answer №1

Pages in Next.js are re-rendered when navigation occurs, causing Apollo Client to be recreated each time. This results in the useQuery component rendering again, checking if the cache has data for the query (which it doesn't because a new client is created) and sending the query anew.

To resolve this issue, consider creating your ApolloClient in the global scope. By doing so, you ensure its stability and enable it to be reused across multiple queries and renders.

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

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

Assign a dynamic class to an element within an ngFor iteration

I am working with a template that includes an app-subscriber component being iterated over using *ngFor: <app-subscriber *ngFor="let stream of streams" [stream]="stream" [session]="session" (speakEvents)='onSpeakEvent($event)'> ...

Avoid data duplication or triplication by implementing a pop-up loop when adding new information

Seeking assistance in identifying the line of code that is causing data duplication or triplication when adding information in a pop-up form. The New/Update/Delete functions are functioning correctly, except for the Add function. The problem arises when i ...

When storing array values in objects, only the first value is saved and is repeatedly replaced with the same value

As a newcomer to JavaScript, my programming skills are not very strong at the moment. I have been working on a web scraper that returns an array of information including names, posts, bios, and more using the following code: let infoOfPost = await newTab(b ...

How to access a controller function within a recursive directive template in Angular version 1.3?

In my parent directive, I am able to access controller functions using the $parent operator. However, this method does not work in recursive child directives. Here is a shortened example of the issue: // Sample controller code (using controllerAs):--- va ...

AngularJS Chrome Extension has been flagged as potentially harmful, despite the implementation of compileProvider.aHrefSanitizationWhitelist. This has resulted

I have previously shared this issue, however, the suggested solutions did not resolve it. Therefore, I am reposting with a more widely recognized solution: I am currently working on developing a chrome extension using AngularJS. In my base directive, I am ...

Having trouble with Angular 2 @input binding?

Parent module: import {NgModule} from '@angular/core'; import {SharedModule} from "app/shared/shared.module.ts"; import {HeaderComponent} from './header.component'; import {UserinfoComponent} from './userinfo.component'; imp ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

The issue with updating values in the jQuery UI datepicker persists

When using the jquery datepicker ui, you may notice that the value attributes of the associated html fields do not update immediately. For example: http://jsfiddle.net/4tXP4/ Check out this link for more details: http://jqueryui.com/demos/datepicker/al ...

Apollo Client is not properly sending non-server-side rendered requests in conjunction with Next.js

I'm facing a challenge where only server-side requests are being transmitted by the Apollo Client. As far as I know, there should be a client created during initialization in the _app file for non-SSR requests, and another when an SSR request is requi ...

"Attempting to dynamically include Components for SSR bundle in React can result in the error message 'Functions are invalid as a React child'. Be cautious of this

When working with my express route, I encountered an issue trying to pass a component for use in a render function that handles Server-Side Rendering (SSR). Express Route: import SettingsConnected from '../../../client/components/settings/settings-c ...

I am experiencing difficulties in accessing the DOM

I have implemented jQuery $.ajax to dynamically load data into table rows as shown below: <table id='row-data'> <tr><td>1001</td></tr> <tr><td>1322</td></tr> <tr><td>15 ...

What is the best way to create an assertion function for validating a discriminated union type in my code?

I have a union type with discriminated properties: type Status = { tag: "Active", /* other props */ } | { tag: "Inactive", /* other props */ } Currently, I need to execute certain code only when in a specific state: // At some po ...

Switch from using fetch to utilizing axios for making API requests

I used fetch for a 'get' request, but now I want to switch to axios. Can someone please help me convert this code to use axios instead? More details: I am fetching an image and using the blob method to display it to the user. I would like to ach ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...