Introduction to GraphQL
GraphQL is a query language to get data from APIs that is more flexible and efficient than REST. Unlike REST, which uses fixed endpoints, GraphQL lets you request exactly the data you need in a single query. This avoids getting too much or too little data, making it perfect for modern applications. When you combine GraphQL with React, it becomes easier to build powerful and interactive user interfaces.
Prerequisites
- Node.js and npm
- React
- Typescript
- Apollo Client
Why Choose GraphQL?
GraphQL is a great tool for building fast and flexible applications. It lets clients fetch only the data they need, which helps reduce unnecessary data and improve performance. Unlike REST APIs, which need different endpoints for different data, GraphQL simplifies things by using a single endpoint.
For developers, GraphQL is easy to use, speeding up development. It also supports real-time updates, which is useful for apps like messaging or news platforms that require live data.
Using GraphQL makes backend management simpler, enhances performance, and speeds up development, ultimately leading to better user experiences and time savings.
Advantages of Using GraphQL
- Efficient Data Fetching : GraphQL only retrieves the data you request, preventing unnecessary data transfer.
- One Endpoint : Instead of multiple REST endpoints, GraphQL uses a single endpoint, simplifying data management.
- Exact Data Requests : You can specify precisely what data you want, which keeps your code organized.
- Real-Time Updates : With subscriptions, GraphQL allows you to get live updates, ideal for apps requiring real-time data.
- Clear Data Structures : GraphQL defines a clear structure, which helps prevent errors, especially with TypeScript.
- Helpful Developer Tools : Tools like Apollo Client add features such as caching and pagination, improving the development experience.
- Multiple Data Sources : You can combine data from different sources in a single request, which simplifies backend management.
- Better App Performance : By reducing unnecessary requests, GraphQL helps improve the app’s speed.

Disadvantages of React Router DOM
- Steeper learning curve, especially for developers used to REST APIs.
- Setup can be more complex in React apps, particularly for caching and error handling.
- Can lead to inefficient queries without proper optimization.
- Managing large or complex queries may negatively impact performance.
- Caching, especially for real-time data, can be challenging to handle effectively.
- Frequent backend schema changes can break the client-side code.
- Potential security risks if sensitive data is not properly secured, as clients can request any data.
Mastering GraphQL with React
Go through the below examples to understand how GraphQL works with React app and what packages are needed to use GraphQL with React.
Start the React App
If you don’t have a React project yet, you can make one like this
//Create react app using the following command
npx create-react-app graphql-with-react --template typescript
//Install the required library
npm install react-router-dom
npm install @apollo/client graphql
How to Use Apollo Client in a React App
Apollo Client is a handy tool for handling GraphQL data in React apps. It simplifies tasks like fetching data, caching it, and managing state without requiring too much extra code. The ApolloClient.ts file is particularly important because it centralizes the setup. Here’s a simple guide to getting started with Apollo Client in your React project.
Set Up Apollo Client
Once the necessary dependencies are installed, you need to configure Apollo Client to interact with your GraphQL server.
Why Create an ApolloClient.ts File?
The ApolloClient.ts file is essential because it centralizes the configuration of the Apollo Client. This means you configure the Apollo Client in one place and can use it throughout your entire application. It simplifies the setup, allows easy updates, and ensures consistency in your app’s data management.
Create ApolloClient.ts
- In your src directory, create a file named ApolloClient.ts (or ApolloClient.js for JavaScript projects).
- Inside this file, configure the Apollo Client instance:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
const httpLink = createHttpLink({
uri: 'Address of GraphQL Server',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
export default client;
Explanation
- httpLink : This is the address of your GraphQL server. It tells Apollo Client where to send the data requests.
- InMemoryCache : Apollo’s caching solution stores data locally, reducing repeated network calls and improving your app’s speed and performance.
- Integrating Apollo Client into React : After setting up your ApolloClient.ts file, the next step is connecting it to your React application. This allows all your components to access and interact with the GraphQL server easily.
Provide Apollo Client to Your React App
Once you have your ApolloClient.ts file set up, the next step is to integrate Apollo Client into your React application.
In your main entry file (either index.tsx or App.tsx), wrap your entire application with the ApolloProvider component, which will make Apollo Client available to all child components.
//index.tsx
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apolloClient';
import App from './App';
ReactDOM.render(
,
document.getElementById('root')
);
To enable React components to communicate with a GraphQL server, wrap the application in an ApolloProvider and pass the client instance. This makes sure every component within the App can seamlessly interact with the server using Apollo Client.
//App.tsx
//Necessary Imports
function App() {
const { loading, error, data } = useQuery(GET_COUNTRIES, {
variables: { code: "IN" },
fetchPolicy: "cache-first",
});
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{Render Fetched Data}
);
}
export default App;
In the App.tsx, data is being fetched for a single country based on a country code. And design the component to display the data accordingly.
Here in the query, we are using one attribute fetchPolicy. When the query is executed, Apollo first checks if the requested data is already in the cache (cache-first). If it’s available, it returns the cached data. If not, it fetches the data from the network and then caches the result for future use.
fetchPolicy Options
- cache-first : Uses cached data if available, otherwise makes a network request.
- network-only : Always makes a network request, bypassing the cache.
- cache-only : Only uses the cache, and won’t make a network request.
- no-cache : Disables caching entirely.
import { gql } from "@apollo/client";
export const GET_COUNTRIES = gql`
query Query ($code: ID!) {
country(code: $code) {
name
native
capital
emoji
currency
languages {
code
name
}
emojiU
}
}
`;
When using GraphQL, you can fetch specific information about a country, such as its name, native name, capital, emoji, currency, languages, and emojiU. This flexibility allows developers to request only the fields they need, ensuring the application remains efficient by avoiding unnecessary data retrieval.

For example :
- If you only need the name and capital of the country, you can modify the query like this:
import { gql } from "@apollo/client";
export const GET_COUNTRIES = gql`
query Query($code: ID!) {
country(code: $code) {
name
capital
}
}
`;

Explanation
- Customizing Data Fetch : By tailoring the fields in your GraphQL query, you can ensure the server returns only the data your application needs. This selective approach boosts performance, particularly when dealing with large datasets.
- Flexibility : As your application evolves, you can easily expand the query to include extra fields, such as native, currency, or languages, without requiring modifications to the backend.
Why Club Multiple Endpoints in a Single GraphQL Query?
Combining multiple endpoints into a single GraphQL query reduces the number of network requests, making data fetching faster. By requesting only the required fields, it avoids transferring unnecessary data. This method also simplifies error handling and development by consolidating logic. Additionally, it improves the user experience by loading data more efficiently, resulting in a more responsive application.
import { gql } from '@apollo/client';
export const GET_COUNTRY_AND_LANGUAGES = gql`
query GetCountryAndLanguages($code: ID!) {
country(code: $code) {
name
capital
}
languages {
code
name
native
}
}
`;
//App.tsx
//Necessary Imports
function App() {
const { loading, error, data } = useQuery(GET_COUNTRY_AND_LANGUAGES, {
variables: { code: "IN" },
fetchPolicy: "cache-first",
});
console.log(data)
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
);
}
export default App;
- Country Query : Fetches details like the name, capital, and currency of a country based on its code.
- Languages Query : Retrieves a list of available languages with their code, name, and native name.

Conclusion
To sum up, using GraphQL with React helps developers fetch and manage data more efficiently. GraphQL allows you to request only the data you need, which improves performance and reduces unnecessary data transfer. React’s component-based structure works well with GraphQL, making it easier to manage data and create interactive UIs. This combination is a flexible way to build modern web applications. By using GraphQL in your React projects, you can boost both developer productivity and user experience.