Ben
Ben

Reputation: 3357

Apollo client useMutation in expo renders twice for every call

I have a basic expo app with React Navigation. In the top function Navigation I am initiating a useMutation call to an Apollo server like so:

import { callToServer, useMutation } from '../graphQL';
function Navigation() {
  console.log("RENDERED");
  const [call] = useMutation(callToServer);

  call({ variables: { uid: 'xyz', phoneNumber: '123' } });
  ...

And my GraphQL settings is as follows:

import {
  ApolloClient,
  createHttpLink,
  InMemoryCache,
  useMutation,
} from '@apollo/client';
import { onError } from '@apollo/client/link/error';

import { callToServer } from './authAPI';

const cache = new InMemoryCache();
const httpLink = createHttpLink({
  uri: `XXXXXXX/my-app/us-central1/graphql`,
});

const errorLink = onError(({ graphQLErrors, networkError }) => {
  ...
});

const client = new ApolloClient({
  cache,
  link: errorLink.concat(httpLink),
});

export {
  useMutation,
  callToServer,
};
export default client;

I want to clarify that I removed the httpLink from the client setting and I still get the two renders per call. I can see in the console that console.log("RENDERED") prints three times. Once when the app loads (normal) and twice after the useMutation call (not normal?)

What's going on here? Why is react re-renders twice per useMutation call? How do I avoid it?

UPDATE

I did further digging and it seems that useMutation does indeed cause the App to render twice - once when the request is sent, and once when it receives a response. I'm not sure I'm loving this default behavior which seems to have no way to disable. Why not let us decide if we want to re-render the App? If someone has more insight to offer, Id love to hear about it.

Upvotes: 1

Views: 1028

Answers (1)

onair_Lena
onair_Lena

Reputation: 45

Probably it's too late and maybe you've already found the solution, but still...

As I see you do not need data returned from mutation in the code above. In this case you can use useMutation option "ignoreResults" and set it to "true". So mutation will not update "data" property and will not cause any render.

Upvotes: 2

Related Questions