docs/graphcache/README.md
In urql, caching is fully configurable via exchanges, and the default
cacheExchange in urql offers a "Document Cache", which is
usually enough for sites that heavily rely on static content. However as an app grows more
complex it's likely that the data and state that urql manages, will also grow more complex and
introduce interdependencies between data.
To solve this problem most GraphQL clients resort to caching data in a normalized format, similar to how data is often structured in Redux.
In urql, normalized caching is an opt-in feature, which is provided by the
@urql/exchange-graphcache package, Graphcache for short.
The following pages introduce different features in Graphcache, which together make it a compelling
alternative to the standard document cache that urql uses by
default.
We can add Graphcache by installing the @urql/exchange-graphcache package.
Using the package won't increase your bundle size by as much as platforms like
Bundlephobia may suggest, since it
shares the dependency on wonka and @urql/core with the framework bindings package, e.g. urql
or @urql/preact, that you're already using.
yarn add @urql/exchange-graphcache
# or
npm install --save @urql/exchange-graphcache
The package exports the cacheExchange which replaces the default cacheExchange in @urql/core.
This new cacheExchange must be instantiated using some options, which are used to customise
Graphcache as introduced in the "Features" section above. However, you can get started
without passing any options.
import { Client, fetchExchange } from 'urql';
import { cacheExchange } from '@urql/exchange-graphcache';
const client = new Client({
url: 'http://localhost:3000/graphql',
exchanges: [cacheExchange({}), fetchExchange],
});
This will automatically enable normalized caching, and you may find that in a lot of cases, Graphcache already does what you'd expect it to do without any additional configuration. We'll explore how to customize and set up different parts of Graphcache on the following pages.