GraphQL requests made easy with React Query and TypeScript

GraphQL requests made easy with React Query and TypeScript

Iva Kop

· 6 min read

Using a GraphQL API comes with distinct advantages. With GraphQL, we can request the exact data we need without ever under- or over-fetching. We can also get multiple resources in a single request. At the same time, the requests themselves can serve as a form of documentation, making it is easy to understand what data is being used, where, and why.

But the most exciting feature of GraphQL is that the API is fully described by its schema, including all data types for each possible query or mutation.

Why does this matter?

Because, based on that schema, we can automatically create TypeScript types for the entire API on the frontend. What’s more is we can easily autogenerate fully-typed custom React hooks for a data-fetching library like React Query .

Let me show you how.

Setting up the project with GraphQL

React app

First, let's create our React project with Create React App with the TypeScript template.

yarn create react-app graphql --template typescript


Next, we need an API. FakeQL provides a great way to create a mock GraphQL API and deploy it. Because we will be using the default definition, we can set everything up simply by clicking Extend JSON and then Deploy. The tool generates a unique URL where we can access our new API.

Data-fetching library

Now that we have our React app and our API, it is time to set up our data-fetching library, React Query.

Let's install it:

yarn add react-query

Now, set up the React Query client.

import { QueryClient, QueryClientProvider } from 'react-query';

import Posts from 'components/Posts';

const queryClient = new QueryClient();

const App = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <Posts />

export default App;


Because our API provides a list of posts, we will use a Posts component to display them. For the moment, let’s leave it empty.

// components/Posts.tsx

const Posts = () => {
  return <></>;

export default Posts;

Next, we need a query to get the list of posts. Let’s define it in a .graphql file and co-locate it with our component:

# components/Posts/posts.graphql

query Posts {
  posts {

Finally, let’s also add a mutation for deleting a post:

# components/Posts/deletePost.graphql

mutation DeletePost($id: ID!) {
    deletePost(id: $id)

Auto-generate typed React Query hooks with TypeScript and GraphQL Codegen

We are now ready to auto-generate our custom and fully typed React Query hooks based on the requests we previously defined in our .graphql files. We will be using GraphQL Code Generator.

We start by installing it:

yarn add graphql
yarn add -D @graphql-codegen/cli

Next, we need to initialize the wizard and go through the steps:

yarn graphql-codegen init

First, we choose the type of app we are building:

Application built with React

Then, we define our schema is by pasting our FakeQL url.

Where is your schema? FakeQL url pasted

We define where our operations and fragments are:

Where are your operations and fragments? src/**/*.graphql

We choose our plugins:

Typescript and Typescript Operations selected

We choose where to write the output:

Where you write the output? src/generated/index.ts

Let’s also generate an introspection file:

Do you want to generate an introspection file? yes

We need to name our config file:

How to name the config file? codegen.yml

Finally, let’s name our script graphql:codegen:

What script in package.json should run the codegen? graphql:codegen

So far, so good!

In order to generate custom React Query hooks, we need to install the appropriate plugin:

yarn add -D @graphql-codegen/typescript-react-query

And add a quick edit of the codegen.yml config file in order to make it work:

overwrite: true
schema: ''
documents: 'src/**/*.graphql'
      - typescript
      - typescript-operations
      - typescript-react-query
        endpoint: ''

Finally, we need to run our script.

yarn graphql:codegen

We are now done! Our fully-typed custom React Query hooks have been automatically generated and added directly to our project’s generated folder.

Let’s see them in action!

Making API requests

In our Posts component, we are now ready to display the list of posts:

import { usePostsQuery } from 'generated';

const Posts = () => {
  const { data } = usePostsQuery();
  return (
      {isLoading && <p>Loading ...</p>}
      {data &&
        data.posts?.map((post) => (
          <div key={post?.id}>
            <hr />

export default Posts;

Let’s also add the DeletePost mutation we defined earlier.

import { useQueryClient } from 'react-query';
import { usePostsQuery, useDeletePostMutation } from 'generated';

const Posts = () => {
  const queryClient = useQueryClient();
  const { data, isLoading } = usePostsQuery();
  const { mutate } = useDeletePostMutation({
    onSuccess: () => queryClient.invalidateQueries('Posts'),

  return (
      {isLoading && <p>Loading ...</p>}
      {data &&
        data.posts?.map((post) => (
          <div key={post?.id}>
            <button onClick={() => post && mutate({ id: })}>
            <hr />

export default Posts;

That’s it, we now have a working example!


The approach described above allows us to take full advantage of GraphQL on the frontend by automating both the creation of TypeScript types for the API and the generation of custom React Query hooks for each request.

By using it, we have also substantially reduced the amount of data-fetching boilerplate code we need to write. With this tooling in place, all we need to do in order to create additional React Query custom hooks for a request is to create a .graphql file and run the graphql:codegen script. Pretty cool, right?

Curious to play with the code yourself? Find a full working example in my GitHub repo .

Happy coding! ✨

Join my newsletter

Subscribe to get my latest content by email.

I will never send you spam. You can unsubscribe at any time.


© 2022 Iva Kop. All rights reserved

Privacy policyRSS