Use GraphQL Query Hooks With React
Hooks reduce the boilerplate of React apps, the same can be done for Apollo with React
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.
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.
To enable Apollo in our project, we create an Apollo client and use
ApolloProvider to inject it into our component tree:
- We create the client with the URL of the remote GraphQL in this case: https://api.graph.cool/simple/v1/swapi. 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?
After having added the client, we need to think about which data we might want to request from this GraphQL endpoint and we can do it easily there.
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
Then, we have to proceed with the final, most beautiful step:
- First, we declare the query created in the previous part to get all first six films as a const variable
STAR_WARS_FILMSon line 6 to 13.
- We apply the
useQueryon line 18, getting back the data of the films inside the data variable renamed
dataFilmsto make it more readable. We then use
- 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!