Unlock the Power of Apollo Client 3: New Features and Caching Capabilities

Revamped InMemoryCache APIs

Apollo Client 3 has introduced significant changes to the InMemoryCache API, featuring improvements such as object and field eviction, garbage collection, types and fields configuration, and pagination helpers.


import { InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        // Example field policy
        exampleField: {
          read(_, { args }) {
            return args.exampleArg;
          },
        },
      },
    },
  },
});

Effortless Cache Management

Apollo Client 3 makes it easy to manage your cache by providing methods like cache.evict, cache.gc, and cache.retain. You can also customize how dangling references are handled using a custom read function.


// Evict a cached item
cache.evict({ id: 'exampleId', __typename: 'ExampleType' });

// Perform garbage collection
cache.gc();

// Retain a specific item
cache.retain({ id: 'exampleId', __typename: 'ExampleType' });

Local State Management

Create your own local fields within the InMemoryCache object, allowing you to include them in your queries alongside loading state and network status. You can also use reactive variables to store local state outside of the Apollo Client cache.


import { makeVar } from '@apollo/client';

// Create a reactive variable
const exampleVar = makeVar('initialValue');

// Update the reactive variable
exampleVar('newValue');

Reactive Variables: A Game-Changer

Reactive variables enable you to store local state outside of the cache and automatically trigger updates to all active queries that depend on them.

Cache Field Policies: Customization Unleashed

Define your own cache field policy to read fields in a way that differs from the API. This feature allows you to modify field values, set default values, transform lists, and more.


import { InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        // Example field policy
        exampleField: {
          read(_, { args }) {
            return args.exampleArg;
          },
        },
      },
    },
  },
});

Additional Resources

Leave a Reply

Your email address will not be published. Required fields are marked *