Generating TypeScript types and React Hooks based on a GraphQL endpoint
Tags: graphql, react, typescript, reacthooks
Published: 2020-09-07 12:42:26

---
title: Generating TypeScript types and React Hooks based on a GraphQL endpoint
published: true
description: Autogenerate Typescript types and custom React hooks in React applications with GraphQL Code Generator.
tags: GraphQL, ReactJS, Typescript, ReactHooks
cover_image: https://danilowoz.com/images/generating-typescript-types-and-react-hooks-based-on-graphql-endpoint/cover.jpg
canonical_url: https://danilowoz.com/blog/generating-typescript-types-and-react-hooks-based-on-graphql-endpoint
---

[<sub><sup>_Cover image by Fred Jesus_</sub></sup>](https://dribbble.com/Fredjesus1)

Nowadays, developing ReactJS with TypeScript gives us a solid way to write applications: it adds the advantage of type-safety, component auto-documentation, error handling, and accurate autocomplete in the editor code. However, it still requires a considerable effort to write types and keep them maintainable. Moreover, when the data provider is a GraphQL server, it makes you feel like you're doing a useless job, given the server already has its own schemas for types. Seem redundant, right?

With this in mind, [GraphQL Code Generator](https://graphql-code-generator.com/) gives us the ability to generate TypesScript typing out of GraphQL schemas. Beyond that, it gives us a couple of plugins to create custom React hooks that don't require any kind of maintenance or workaround to fit into your application.

Among many others, some of the benefits of using this tool:

- **Codeless:** forget about creating the interfaces/types for every GraphQL endpoints; save time and spend effort on what matters;
- **Development experience:** as a result of having the types always available, your editor will provide meaningful autocomplete and error checking;
- **Types always up-to-date:** if your GraphQL endpoint schemas change, your application will be updated and typescript will help you make sure you make the necessary changes.

## Setup

First of all, let's install the dependencies needed:

```sh
npm i @apollo/react-hooks graphql
```

```sh
npm i @graphql-codegen/cli @graphql-codegen/import-types-preset @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --save-dev
```

I'm considering the following folder structure, but of course, feel free to adapt it to your liking, just have in mind that it needs a place to store the schemas that will be fetched by the Code Generator:

```
📦 my-project
┣ 📂 src
┃ ┣ 📂 pages
┃ ┃ ┗ index.tsx
┃ ┣ 📂 queries
┃ ┃ ┣ 📂 autogenerate
┃ ┃ ┗ my-query.gql
┃ ┗ apollo-client.ts
┣ codegen.yml
┗ package.json
```

Then, basically, you'll need to create a configuration file at the root of the project, named codegen.yml. The following snippet shows how I usually set it up in my projects, where it generates different files for its own purpose, in other words, split by concerns like GraphQL operations and server schemas:

```yaml
# Endpoint API, the following URL is a example
schema: https://countries-274616.ew.r.appspot.com/graphql/
overwrite: true
# Format files
hooks:
  afterAllFileWrite:
    - prettier --write
generates:
  # Get schemas from server
  src/queries/autogenerate/schemas.tsx:
    documents: 'src/queries/**/**.gql'
    plugins:
      - typescript
  # Create operations based on queries
  src/queries/autogenerate/operations.tsx:
    documents: 'src/queries/**/**.gql'
    preset: import-types
    presetConfig:
      typesPath: ./schemas
    plugins:
      - typescript-operations
  # 1. Export GraphQL documents
  # 2. React interface
  src/queries/autogenerate/hooks.tsx:
    documents: 'src/queries/**/**.gql'
    preset: import-types
    presetConfig:
      typesPath: ./operations
    plugins:
      - typescript-react-apollo
    config:
      # Optionals
      withHOC: false
      withComponent: false
      withHooks: true
```
Also, let's add the scripts to generate the schemas and watch the files change in package.json:

```json
"scripts": {
  ...
  "schemas": "graphql-codegen --config codegen.yml",
  "schemas:watch": "npm run schemas -- --watch",
},
```
And as it turns out in the editor code:
![Live coding](https://dev-to-uploads.s3.amazonaws.com/i/pyajp9i01gsl4rvkj9qb.gif)

This is only one of the possible ways to use it, as it has many plugins, presets, integrations, and configurations, for different purposes such as to generate React higher-order component, Gatsby integration, prettier and lint the files, among other cool things. Feel free to check out the documentation [here](https://graphql-code-generator.com/).

I've made a repository available with the code above, and you can [check it out here](https://github.com/danilowoz/ts-gql-jsx).

---

Originally published at [danilowoz.com](https://danilowoz.com/)

---