React-apollo: useQuery hook fetches data twice

Created on 1 Apr 2020  ·  10Comments  ·  Source: apollographql/react-apollo

Intended outcome:
Get data from graphql server provided by graphql documentation using useQuery hook from @apollo/react-hooks

Actual outcome:
The data is fetched twice instead of once.

How to reproduce the issue:
I have created a simple react app in codesandbox that you can open up using the link below:
https://codesandbox.io/s/infallible-pasteur-wq3zp
Here is the screenshot of my logs. You can see that the data object is returned twice:
image

I have also tried to use apollo/client from beta docs, but the result is the same.

Version


System:
OS: Windows 10 10.0.19587
Binaries:
Node: 12.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.13.4 - C:\Program Files\nodejs\npm.CMD
Browsers:
Edge: 44.19587.1000.0
npmPackages:
apollo-boost: ^0.4.7 => 0.4.7

All 10 comments

The console.log statement may be running twice, but your data is only being fetched once. If you look at the Network tab in your browser's dev tools then you'll see that there's only one request being made to 48p1r2roz4.sse.codesandbox.io. The reason the console.log statement is running twice is because you have it set up to call console.log every time TestComponent renders, and it renders twice after receiving data.

Thank you for your responce @dylanwulf ! Is it a normal behavior for a component to render twice? I was expecting it to render once...

The extra render might not be necessary in your case, but apollo-client is probably updating some other values that you're not reading and that's why you see it render a second time. An extra render will not affect the appearance of your component at all, and should be negligible in terms of performance.

It looks like it only works because of caching...If I try to send a unique request for each render - I end up having an infinite number of requests. And I also found out that I cannot disable cache by setting no-cache fetch policy.

Same issue for me as well, I am able to see four console logs

image

and last one is

image

I'm seeing duplicate renders as well. Both renders happen after query loading has finished.

Isn't this problem related to ?

@JunHyeokHa it is indeed! Thank you!

Any workaround for this?. rendering twice is causing issues in infinite scroll

@mohammed-shameem As @JunHyeokHa mentioned the problem is related to React Strict mode. So you can disable it, if it is not necessary for your project.

Was this page helpful?
0 / 5 - 0 ratings