Marcin Falkowski
1/31/2024
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.
To understand the key of this combination let's delve into the integration of the Apollo Client and GraphQL in Codegen and their roles:
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.
yarn add @apollo/client graphql
or npm i @apollo/client graphql
Remember about Pods! Use the pod install
command after installation
src
directory, create a new folder graphql
with a apolloClient.ts
file insideapolloClient.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(),
});
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:
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
*.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.
package.json
"scripts": {
{...}
"codegen": "graphql-codegen --config graphql.config.yml"
},
Congratulations! You have finished configuring GraphQL Codegen!
queries
in the graphql folder. Inside the queries
folder, create a new file named query.ts
.import { gql } from '@apollo/client';
export const Example = gql`
query Example {
company {
ceo
coo
cto
founder
}
roadster {
name
launch_date_utc
earth_distance_km
}
}
`;
yarn codegen
. If you can see this input, everything is working properly!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!
The result of the query is also typed:
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!