Use GraphQL Query Hooks With React

Hooks reduce the boilerplate of React apps, the same can be done for Apollo with React

Riccardo Giorato
Sep 26, 2019 · 4 min read

GraphQL and Apollo are a great combination of tools to be used with React! GraphQL makes it easier to get, modify, or get a realtime feed of your data from the servers. It’s also entirely open-source standard.

Apollo provides a suite of easy tools to implement everything related to GraphQL in React and it’s also open-source hosted on GitHub.

More recently, Apollo released an update introducing React Hooks, this has drastically reduced the code needed to use GraphQL, making it ten times simpler to use queries, subscriptions, and mutations in React.

Final Result

You can get the final application here:


Apollo Dependencies

Apollo needs a few dependencies to provide all the tooling required for GraphQL, you need to open the terminal and type:

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

The functionalities brought by these packages are:

  • apollo-boost: Package containing everything you need to set up the Apollo client.
  • @apollo/react-hooks: React Hooks-based view layer integration.
  • graphql: Parses your GraphQL queries.

Apollo Client

  • We create the client with the URL of the remote GraphQL in this case: You can see it on the tenth line.
  • Then, we add the ApolloProvider, its power is that the client will be automatically passed as a singleton on every component inside the app component.


What Should I Query?

We might want to request the first three or six films, changing the parameter “first”, we then select different information like the title or the release date.

Get and Show the Data

  • First, we declare the query created in the previous part to get all first six films as a const variable STAR_WARS_FILMS on line 6 to 13.
  • We apply the useQuery on line 18, getting back the data of the films inside the data variable renamed dataFilms to make it more readable. We then use dataFilms as a simple JavaScript array.
  • We show those titles or bits of information inside the return of the render.
  • You can also use the error or loading variable to understand if the data from the server is loading or if it returned an error.


And voilà! Our app is now working wonderfully!

If you want to learn more about Hooks

Better Programming

Advice for programmers.

Riccardo Giorato

Written by

XR Developer and Photogrammetry Artist

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade