useMutation hook usage in apollo v4

Hi, regarding the migration to apollo client v4, the migration guide says

As a result, we now recommend the use of core APIs directly in several use cases where synchronization with a component is not needed or intended.

https://www.apollographql.com/docs/react/migrating/apollo-client-4-migration#a-note-about-hook-usage

Does this rule apply also to useMutation hook? For example, if I have the following:

const MyComponent = () => {
  const [mutate] = useMutation(...)
  
  const myAction = async () => {
    await mutate()
  }

  return null
}

Is it ok, or since I’m not accessing the data it’s better to handle it with client.mutate directly? E.g.

const MyComponent = () => {
  const client = useApolloClient()
  
  const myAction = async () => {
    await client.mutate({ mutation: MUTATION })
  }

  return null
}

Hey @raxell :waving_hand:

Yes, this rule applies to useMutation as well, though seems we forgot to include a snippet on the actual mutations page. In your case, you’re using the mutate function returned from useMutation, but you aren’t reading the state-based values returned from that hook (i.e. data, loading, etc.) so you’re re-rendering your component for changes to values you don’t use.

Since the core API isn’t interacting with React state, your component won’t re-render just for executing the mutation. Hope that helps clarify!

Yeah now it’s clear, thank you!

1 Like

I have another doubt regarding useMutation and the changes in errorPolicy: https://www.apollographql.com/docs/react/migrating/apollo-client-4-migration#changes-to-promise-resolution-with-errors-for-the-execute-function

Are those only related to useLazyQuery or to other operations too?

Error-related promise behavior should be consistent everywhere now, but some query-type promises won’t throw “unhandled promise rejections” if you never await or chain off of them.

1 Like