using react hooks in apollo

Thomas Farla
2 min readDec 30, 2018

So you are exicted about react hooks and want to implement them in your next apollo powered React app? To start simple. Let’s start with the create react app toolkit. This article will use the typescript variant. We’ll use the apollo cli to generate types from a graphql server so we get static analyses on our queries.

Fetching data using query components

First we are going to setup the codebase without hooks and use the react apollo query components instead just to get a reference on how much cleaner the code looks with hooks. Install apollo by executing the following command in the root of the project:

npm install apollo-boost apollo react-apollo graphql @types/graphql

Configure the apollo client in the index.tsx file and wrap the application in the ApolloProvider.

Create a new file and define a variable with the value of the graphql query to execute.

Use the apollo cli to generate type definitions.

apollo service:download --endpoint=https://fakerql.com/graphql
apollo client:codegen --target=typescript --localSchemaFile=\"./schema.json\"

Now we can extends the Query component and add the type definitions for static analyses

Now we can use this GetTodosQuery component to render all todos.

Replace the query component with hooks

To use hooks we need to install the react alpha and react apollo hooks.

npm install react@next react-dom@next react-apollo-hooks

Create a new function which returns the useQuery function with our type definitions we generated earlier

This hook allows us to refactor the Todos component to the following.

Note that the useTodosQuery takes no query argument like the query component does. The function always uses the same query which is less error prone. The hook is also reliant on the suspense api which is a new way to deal with loading states. Let’s compare the Todos component using a query component against the hook.

diff can be found here

React suspense allows us to delegate the loading state to another component and deal with it more elegantly. Hooks also get rid of the render prop and makes the code easier to read from top to bottom.

Summary

I’m excited to use hooks in React. They make code easier to read by injecting behaviour and remove the need to extend React’s component classes. Using them with apollo has been a blast. The full repository including tests can be found here.

--

--