What Is InMemory Cache in Apollo: Simple Explanation and Example
InMemoryCache is a built-in caching system that stores GraphQL query results in memory on the client side. It helps speed up your app by reusing data without asking the server again, making your app faster and more efficient.How It Works
Imagine you have a notebook where you write down answers to questions you ask often. Instead of asking the same question again, you just look it up in your notebook. InMemoryCache works like that notebook for your app's data.
When your app asks the server for data using GraphQL, Apollo saves the response in this cache. Next time your app needs the same data, it checks the cache first. If the data is there and still fresh, Apollo gives it to your app immediately without waiting for the server.
This makes your app feel faster and reduces the number of times it talks to the server, saving bandwidth and improving user experience.
Example
This example shows how to set up Apollo Client with InMemoryCache and fetch data from a GraphQL server.
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://example.com/graphql', cache: new InMemoryCache(), }); client.query({ query: gql`query GetBooks { books { id title author } }` }).then(response => { console.log('Books:', response.data.books); });
When to Use
Use InMemoryCache when you want your app to load data quickly and reduce repeated network requests. It is great for apps where data doesn't change every second, like blogs, product catalogs, or user profiles.
For example, if your app shows a list of books or movies, caching the data means users can browse faster without waiting for the server each time. It also helps when users go back and forth between pages, as the data is already stored in memory.
Key Points
- InMemoryCache stores GraphQL query results in the client’s memory.
- It speeds up apps by avoiding unnecessary server requests.
- It keeps data fresh but can be configured to update when needed.
- Ideal for apps with mostly static or slowly changing data.