Client Reference: updating your Apollo queries to hooks

This post is reference material for past clients we’ve had at Drover. You may find it helpful if you are working on a project using React, Apollo, and TypeScript.

This post details how to convert your queries to hooks, following the patterns we use on our projects. The master article about upgrading your entire app to use Apollo hooks is here.

Declaring and using your query

We only have to make a few changes when converting from the Query component to the useQuery hook. Instead of passing our generated types to the component, we pass them to the hook. Instead of passing our query options as props to the component, we pass them as an argument to the hook.

Before the conversion, a query implemented with the Query component:

After the conversion, a query implemented with the useQuery hook:

Note that by the end of the migration, you’ll be importing from @apollo/react-hooks. At this point in the process, we are still importing from react-apollo.

A note about useLazyQuery and useApolloClient

If you are manually firing queries in your application, you have one more step to take. The most common use case for executing a query on demand like this is waiting for a user action, such as a button click, to trigger execution of an expensive query.

In Apollo version 2, there are two common ways to achieve this extra control over query execution:

  1. using the Apollo client directly to fire a query ( client accessed via ApolloConsumer, withApollo higher order component, etc.)
  2. using conditional rendering and some state management to render a Query component only after some user action.

If you are using any of the client based strategies to manually fire a query, the simplest transition to hooks would be to firing the query with the client, but to access the client via the useApolloClient hook (docs here).

However, the recommended approach for executing a query in response to an event is the useLazyQuery hook, which is dedicated to this use case. Docs for useLazyQuery can be found here.

Once you’ve finished converting your queries and verifying expected behavior, you’ve completed this step. To continue, head back to the main migration article here. If you have any questions, ask in the comment section or reference this blog post in an email to team@droverlabs.com.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store