Log in to GraphQL EditorGet started
Apollo + GraphQL Codegen implementation into a React Native application

Marcin Falkowski

1/31/2024

Apollo + GraphQL Codegen implementation into a React Native application

Staying ahead of trends is crucial to delivering efficient and scalable solutions, especially in the ever-evolving landscape of mobile app development. One such advancement that has gained prominence is the integration of Apollo client and GraphQL into React Native applications and it offers numerous benefits. It not only streamlines data fetching and updating but also simplifies the development process by offering a single, comprehensive endpoint for data retrieval. This approach leads to codebases that are easy to maintain and scale, which is a key factor for any successful mobile app.

Why Apollo & GraphQL Codegen

To understand the key of this combination let's delve into the integration of the Apollo Client and GraphQL in Codegen and their roles:

  • Apollo Client facilitates the efficient management of data in the user interface, ensuring that components are only re-rendered when necessary and provides the ability to cache data
  • GraphQL Codegen automates the generation of secure code based on the GraphQL schema, reducing the likelihood of runtime errors and enhancing the overall developer experience

But why do we need such solutions in our React Native applications? The answer lies in the quest for a more maintainable and scalable code base. Apollo and GraphQL Code Generator (Codegen) work in tandem to enforce type safety, eliminate common pitfalls and streamline the development workflow. In the field of mobile app development, where the most important factors are responsiveness and performance, the integration of these tools can significantly improve the quality of React Native apps.

In this article, we will explore the step-by-step process of implementing Apollo and GraphQL Codegen in a React Native project, discovering their potential to improve the performance and maintainability of mobile apps.

Initialization of Apollo Client

  1. Navigate to the project root directory and install Apollo Client and graphql module using yarn add @apollo/client graphql or npm i @apollo/client graphql

Remember about Pods! Use the pod install command after installation

  1. Inside the src directory, create a new folder graphql with a apolloClient.ts file inside
  2. Create a new instance inside the apolloClient.ts file by using the new ApolloClient command like so:
import { ApolloClient, InMemoryCache } from '@apollo/client';

export const client = new ApolloClient({
  uri: 'https://spacex-production.up.railway.app/',
  cache: new InMemoryCache(),
});
  1. Wrap your application at the topmost level with a ApolloProvider component using the client as prop like this:
import { ApolloProvider } from '@apollo/client';
import { client } from './graphql/apolloClient';
import { Screen } from './Screen';

const App: React.FC = () => {
  return (
    <ApolloProvider client={client}>
      <Screen />
    </ApolloProvider>
  );
};

That's it! The Apollo Client instance has now been implemented. The next step is:

Initialization of GraphQL Code Generator / GraphQL Codegen

  1. Go to the project root directory and install Codegen with sub modules using either yarn or npm:
  • yarn add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-graphql-request @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
  • npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-graphql-request @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
  1. Have the Codegen CLI scan all the *.ts files in the source directory to find all queries and mutations. GraphQL Codegen will use them to generate typesafe hooks that take care of all backend calls. The resulting types and hooks will be created in ./src/graphql/graphql.ts. To automate this process, create a new file called graphql.config.yml using this code:
schema:
	- "https://spacex-production.up.railway.app/"
documents:
	- "./src/**/*.ts"
generates:
	./src/graphql/graphql.ts:
		plugins:
			- typescript
			- typescript-operations
			- typescript-react-apollo

You can find more information about this file in the graphql.config.yml docs.

  1. Add script to package.json
"scripts": {
	{...}
	"codegen": "graphql-codegen --config graphql.config.yml"
},

Congratulations! You have finished configuring GraphQL Codegen!

Time to generate your types!

  1. Add a new folder called queries in the graphql folder. Inside the queries folder, create a new file named query.ts.
  2. Define a graphql query in the newly created file like this:
import { gql } from '@apollo/client';

export const Example = gql`
  query Example {
    company {
      ceo
      coo
      cto
      founder
    }
    roadster {
      name
      launch_date_utc
      earth_distance_km
    }
  }
`;
  1. Run yarn codegen. If you can see this input, everything is working properly!GraphQL Codegen input

How to use this?

Remember the query.ts file? We have defined an example query there. Let's use it in our app! All queries and mutations are implemented as hooks with names similar to the gql object names. All you have to do, is to import a named useQuery hook. In our Example query the generated hook is named useExampleQuery. let's import that from the generated graphql.ts file! It's really simple!

import { useExampleQuery } from './graphql/graphql';
import { SafeAreaView, Text, View, ActivityIndicator } from 'react-native';

export const Screen: React.FC = () => {
  const { data, loading, error } = useExampleQuery();

  if (loading) return <ActivityIndicator />;
  if (error) return <Text>Error from useExampleQuery hook</Text>;

  return (
    <SafeAreaView>
      <View style={{ gap: 10 }}>
        <Text>SpaceX:</Text>
        <Text>CEO {data?.company?.ceo}</Text>
        <Text>COO {data?.company?.coo}</Text>
        <Text>CTO {data?.company?.cto}</Text>
        <Text>Founder {data?.company?.founder}</Text>
      </View>
      <View style={{ gap: 10 }}>
        <Text>Roadster:</Text>
        <Text>NAME {data?.roadster?.name}</Text>
        <Text>LAUNCH DATE{data?.roadster?.launch_date_utc}</Text>
        <Text>EARTH DISTANCE{data?.roadster?.earth_distance_km}</Text>
      </View>
    </SafeAreaView>
  );
};

And that's it! Apollo Client + GraphQL Codegen

The result of the query is also typed: Result of Apollo Query

Conclusion

In summary, the use of GraphQL, Apollo Client combined with GraphQL Codegen in React Native applications provides a number of advantages in mobile app development. By leveraging the performance of GraphQL for data retrieval and the robust client-side management provided by Apollo, developers can create highly responsive, scalable and maintainable mobile applications. This integration not only streamlines the data retrieval process, but also enhances the developer experience with enforced type safety and automatic code generation by GraphQL Code Generator. As the mobile app market evolves, the inclusion of these technologies becomes a necessity, offering a compelling solution to meet the ever-growing demands of modern app development.

Code base: Github Repository

Enjoy!

Check out our other blogposts

Unlocking the Power of React 19
Tomasz Gajda
Tomasz Gajda
Unlocking the Power of React 19
1 min read
about 1 month ago
Zeus update - GraphQL spread operator
Michał Tyszkiewicz
Michał Tyszkiewicz
Zeus update - GraphQL spread operator
1 min read
3 months ago
What is GraphQL Zeus?
Michał Tyszkiewicz
Michał Tyszkiewicz
What is GraphQL Zeus?
1 min read
3 months ago

Ready for take-off?

Elevate your work with our editor that combines world-class visual graph, documentation and API console

Get Started with GraphQL Editor