<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Rijen Manandhar</title>
    <description>The latest articles on Forem by Rijen Manandhar (@rijen_manandhar_e142720fb).</description>
    <link>https://forem.com/rijen_manandhar_e142720fb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2146294%2F02262d04-d66b-4f49-92fc-d6d125b20bb3.jpg</url>
      <title>Forem: Rijen Manandhar</title>
      <link>https://forem.com/rijen_manandhar_e142720fb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rijen_manandhar_e142720fb"/>
    <language>en</language>
    <item>
      <title>Boost Your React Development with GraphQL and Codegen</title>
      <dc:creator>Rijen Manandhar</dc:creator>
      <pubDate>Tue, 01 Oct 2024 08:58:22 +0000</pubDate>
      <link>https://forem.com/rijen_manandhar_e142720fb/boost-your-react-development-with-graphql-and-codegen-55p2</link>
      <guid>https://forem.com/rijen_manandhar_e142720fb/boost-your-react-development-with-graphql-and-codegen-55p2</guid>
      <description>&lt;p&gt;In modern web development, GraphQL has become a popular choice for API interactions, especially when working with complex and flexible data needs. Its ability to fetch exactly what you want — no more, no less — makes it a perfect match for the highly modular and component-driven architecture of React.&lt;/p&gt;

&lt;p&gt;But while GraphQL provides powerful flexibility, it can also introduce the risk of errors, especially when your queries are not in sync with the schema. That’s where GraphQL Code Generator (or Codegen) comes in. It automatically generates TypeScript typings, hooks, and components for your queries based on your schema, improving type safety and speeding up development.&lt;br&gt;
In this article, we'll go over how to set up GraphQL in a React project with Codegen to supercharge your workflow.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Use GraphQL with Codegen?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Before diving into the implementation, let's quickly understand why GraphQL with Codegen is such a powerful combination:&lt;/li&gt;
&lt;li&gt;Type Safety: GraphQL Codegen automatically generates TypeScript types based on your GraphQL schema, eliminating manual type definition and reducing bugs caused by inconsistent types.&lt;/li&gt;
&lt;li&gt;Auto-Generated Hooks: Codegen can create React hooks for your GraphQL queries, making it seamless to integrate queries and mutations directly into your components.&lt;/li&gt;
&lt;li&gt;Productivity Boost: With auto-generated types, components, and hooks, you’ll spend less time writing boilerplate code and more time focusing on building features.&lt;/li&gt;
&lt;li&gt;Error Reduction: Codegen helps eliminate runtime errors by ensuring your queries are always in sync with the API schema, allowing you to catch issues during compile time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, let's get hands-on.&lt;/p&gt;
&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;We’ll walk through setting up a React app with Apollo Client, GraphQL, and GraphQL Code Generator to automatically generate hooks and types.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Setting Up the Project
&lt;/h3&gt;

&lt;p&gt;First, create a new React app if you don’t have one yet. We are going to use vite in this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn create vite graphql-codegen-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, install the required dependencies for GraphQL and Apollo Client:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add @apollo/client graphql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;a href="https://www.npmjs.com/package/@apollo/client" rel="noopener noreferrer"&gt;@apollo/client&lt;/a&gt; package allows to create GraphQL client that interacts with your schema, including fetching data, caching, and managing subscriptions and &lt;a href="https://www.npmjs.com/package/graphql" rel="noopener noreferrer"&gt;graphql&lt;/a&gt; package allows to define your GraphQL schema, including types, queries, mutations, and subscriptions.&lt;br&gt;
Now, install the GraphQL Code Generator and the necessary plugins:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add --dev @graphql-codegen/cli @graphql-codegen/client-preset
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are installing these packages as a dev dependency. Here, &lt;br&gt;
&lt;a href="https://www.npmjs.com/package/@graphql-codegen/cli" rel="noopener noreferrer"&gt;@graphql-codegen/cli&lt;/a&gt; is the command-line interface (CLI) for GraphQL Code Generator and &lt;a href="https://www.npmjs.com/package/@graphql-codegen/client-preset" rel="noopener noreferrer"&gt;@graphql-codegen/client-preset&lt;/a&gt; is a preset for GraphQL Code Generator, specifically designed for generating client-side code such as TypeScript types.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 2: Configuring Apollo Client
&lt;/h3&gt;

&lt;p&gt;To use apollo client within our application we need to configure apollo client and wrap it around the app in &lt;code&gt;main.tsx&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import ReactDOM from 'react-dom/client'
import { ApolloClient, ApolloProvider, InMemoryCache } from "@apollo/client"

import App from './App.tsx'

import './index.css'

//You can configure in separate file
const client = new ApolloClient({
  uri: 'https://graphql-pokeapi.graphcdn.app/graphql', // Replace with your GraphQL API endpoint
  cache: new InMemoryCache(),
});

ReactDOM.createRoot(document.getElementById('root')!).render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;ApolloProvider client={client}&amp;gt;
      &amp;lt;App /&amp;gt;
    &amp;lt;/ApolloProvider&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;,
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3: Setting Up Codegen
&lt;/h3&gt;

&lt;p&gt;To configure GraphQL Codegen, create a file called &lt;code&gt;codegen.yml&lt;/code&gt; in the root of your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;schema: 'https://graphql-pokeapi.graphcdn.app/graphql'  # Replace with your GraphQL API endpoint
documents: ['src/**/*.{ts,tsx}']
generates:
  ./src/__generated__/:
    preset: 'client'
    plugin: []
    presetConfig: 
        gqlTagName: 'gql'
ignoreNoDocuments: true,
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;schema&lt;/strong&gt;: This specifies the URL of the GraphQL API endpoint that the generator will use to fetch the schema. In this case, it's set to &lt;a href="https://graphql-pokeapi.graphcdn.app/graphql" rel="noopener noreferrer"&gt;https://graphql-pokeapi.graphcdn.app/graphql&lt;/a&gt;, which is a public GraphQL API for Pokemon data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;documents&lt;/strong&gt;: This specifies the location of the GraphQL query documents (i.e., .ts or .tsx files) that the generator will use to generate code. The src/*&lt;em&gt;/&lt;/em&gt;.{ts,tsx} pattern means the generator will look for files with .ts or .tsx extensions in the src directory and all its subdirectories.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;generates&lt;/strong&gt;: This section specifies the output configuration for the generated code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;./src/&lt;strong&gt;generated&lt;/strong&gt;/&lt;/strong&gt;: This is the output directory where the generated code will be written.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;preset: 'client'&lt;/strong&gt;: This specifies the preset 
  configuration for the generator. In this case, it's set 
  to client, which means the generator will produce code 
  optimized for a client-side application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;plugin&lt;/strong&gt;: []: This is an empty array, which means no 
 additional plugins are being used to customize the 
 generation process.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;presetConfig&lt;/strong&gt;: This section specifies additional 
 configuration options for the preset.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;gqlTagName: 'gql'&lt;/strong&gt;: This specifies the tag name to use 
 for GraphQL tagged template literals. In this case, it's 
 set to gql, which means the generated code will use gql as 
 the tag name for GraphQL queries.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;ignoreNoDocuments&lt;/strong&gt;: This flag is set to true, which means the generator will ignore files that don't contain any GraphQL documents (i.e., queries or mutations). This can be useful if you have files in your src directory that don't contain GraphQL code.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 4: Add the codegen script
&lt;/h3&gt;

&lt;p&gt;Add a codegen script into your &lt;code&gt;package.json&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"generate": "graphql-codegen"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run the script in your terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn generate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will generate a folder named &lt;code&gt;__generated__&lt;/code&gt; inside &lt;code&gt;src&lt;/code&gt; folder which includes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;fragment-masking&lt;/strong&gt;: This file contains generated TypeScript types and utilities for fragment masking. Fragment masking is a technique to selectively retrieve only the necessary fields from a GraphQL fragment, reducing the amount of data transferred between the client and server. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;gql&lt;/strong&gt;: This file contains the GraphQL schema definitions, such as queries, mutations, and subscriptions, in a string format. The .gql files are used as input for the GraphQL Code Generator to generate TypeScript types and other artifacts. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;graphql&lt;/strong&gt;: This file contains generated GraphQL-related code, such as resolvers, schema definitions, or other utility functions. The graphql files might include generated code for Apollo Client, GraphQL hooks, or other GraphQL-related libraries. &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step 5: Writing a GraphQL Query
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;graphql/queries&lt;/code&gt; folder inside &lt;code&gt;src&lt;/code&gt; and add a sample GraphQL query. In this example, let’s query a list of pokemons:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { gql } from "../__generated__";

export const GET_POKEMON = gql(`
query pokemons($limit: Int, $offset: Int) {
  pokemons(limit: $limit, offset: $offset) {
    count
    next
    previous
    status
    message
    results {
      url
      name
      image
    }
  }
}
`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run &lt;code&gt;yarn generate&lt;/code&gt; once again. This will generate all the types for your query inside the graphql folder.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 6: Integrate the query inside the component
&lt;/h4&gt;

&lt;p&gt;Once we have generate the type, we can make use of &lt;code&gt;useQuery&lt;/code&gt; hook from &lt;code&gt;@apollo/client&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useQuery } from '@apollo/client'
import { GET_POKEMON } from './graphql/query'

function App() {
  const { data, loading } = useQuery(GET_POKEMON);

  if (loading) {
    return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;
  }
  return (
    &amp;lt;&amp;gt;
      &amp;lt;h1&amp;gt;Pokemon List&amp;lt;/h1&amp;gt;
      {
        data?.pokemons?.results?.length ?
          data?.pokemons?.results?.map(pokemon =&amp;gt; (
            &amp;lt;p key={pokemon?.name}&amp;gt;
              {pokemon?.name}
            &amp;lt;/p&amp;gt;
          )) : null
      }
    &amp;lt;/&amp;gt;
  )
}

export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By combining GraphQL and Codegen, you can dramatically improve the type safety, speed, and productivity of your React development process. This setup ensures that your code is always in sync with your GraphQL schema, reduces the chances of runtime errors, and saves you from writing repetitive boilerplate code.&lt;br&gt;
Whether you're working on large-scale applications or small projects, this workflow will streamline your development and allow you to focus on building features instead of worrying about manual type management.&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>react</category>
      <category>typescript</category>
      <category>codegen</category>
    </item>
  </channel>
</rss>
