GraphQL Fundamentals and Apollo Client Setup0%

GraphQL Fundamentals and Apollo Client Setup

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

GraphQL Fundamentals and Apollo Client Setup

REST APIs often suffer from two enterprise scale challenges: over-fetching (retrieving hundreds of unused object fields) and under-fetching (requiring multiple waterfall HTTP requests to assemble related relational data). GraphQL solves this by providing a declarative query language where the client specifies the exact shape of data required. Apollo Client is the premier state management and caching client for GraphQL in React.


1. Core GraphQL Concepts

  • Schema & Types: The strongly-typed contract defined on the server (type User { id: ID!, name: String!, email: String! }).
  • Queries: Read operations fetching specific fields:
GRAPHQL
query GetUserData {
user(id: "123") {
name
email
}
}
  • Mutations: Write operations creating, updating, or deleting data.
  • Subscriptions: Persistent real-time event streams over WebSockets.

2. Apollo Client Architecture & Normalized Cache

Unlike standard HTTP caches that store responses by raw URL endpoint string, Apollo Client's Normalized In-Memory Cache (InMemoryCache):

  1. 1
    Deconstructs incoming GraphQL JSON responses into individual records.
  2. 2
    Generates a unique key for each entity (by default: __typename:id, e.g. User:123).
  3. 3
    Normalizes and stores each entity in a flat key-value dictionary.
  4. 4
    If two queries request different fields of User:123, Apollo automatically merges them into a single coherent entity in memory!
Output
Incoming Query Response:
{ user: { __typename: "User", id: "123", name: "Alice" } }
 
Normalized Cache Store:
"User:123" ──► { __typename: "User", id: "123", name: "Alice" }

3. Configuring Apollo Client with Authentication Headers

Bash / Terminal
npm install @apollo/client graphql
TSX
// src/lib/apolloClient.ts
import { ApolloClient, InMemoryCache, createHttpLink, ApolloProvider } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
 
// 1. HTTP connection to GraphQL endpoint
const httpLink = createHttpLink({
uri: "https://api.enterprise.com/graphql",
});
 
// 2. Auth Link: Injects Bearer token dynamically into HTTP headers
const authLink = setContext((_, { headers }) => {
const token = sessionStorage.getItem("access_token");
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
 
// 3. Instantiate Apollo Client with normalized cache
export const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
// Custom pagination merge policy
allProjects: {
keyArgs: false,
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
}),
});

4. Wrapping the Application with ApolloProvider

TSX
import React from "react";
import ReactDOM from "react-dom/client";
import { ApolloProvider } from "@apollo/client";
import { apolloClient } from "./lib/apolloClient";
import { App } from "./App";
 
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ApolloProvider client={apolloClient}>
<App />
</ApolloProvider>
</React.StrictMode>
);

Any child component within this tree can now execute GraphQL operations via hooks (useQuery, useMutation, useSubscription).


Interactive Quiz

Practice Quiz

Question 1
What is the primary problem of "over-fetching" in traditional REST APIs?
Question 2
How does Apollo Client's InMemoryCache normalize incoming data entities?
Question 3
What is the purpose of Apollo's setContext link in the client configuration?
Question 4
What happens if two separate queries request different fields for the exact same entity id?
Question 5
What is the GraphQL equivalent of an HTTP POST / PUT / DELETE operation in REST?
Next Lesson

Executing GraphQL Queries with useQuery

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext