patterntypescriptgraphqlMajor
Apollo Client cache normalization — understand __typename and keyFields
Viewed 0 times
Apollo Client 3.x
InMemoryCachenormalizationkeyFieldscache.modifycache.identify__typenametypePolicies
Problem
Apollo Client's InMemoryCache stores results by a cache key derived from
__typename and id. Without understanding this, queries that return the same entity under different keys don't share cached data, causing stale displays after mutations.Solution
Ensure every query requests
id (or the key field) alongside __typename. Configure keyFields for types with non-standard keys.const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Product: {
keyFields: ['sku'], // use 'sku' instead of 'id'
},
Query: {
fields: {
users: relayStylePagination(), // merge paginated results
},
},
},
}),
});
// After a mutation, update the cache
const [updateUser] = useMutation(UPDATE_USER, {
update(cache, { data }) {
cache.modify({
id: cache.identify(data.updateUser),
fields: { name: () => data.updateUser.name },
});
},
});Why
Apollo normalizes results into a flat store keyed by
TypeName:id. Two queries returning the same User automatically share cached data. Mutations that update an entity automatically propagate to all queries that included that entity.Gotchas
- Always include
idin every selection set that returns an object type — missing it breaks normalization - List fields (like
users) are not automatically merged with pagination — configure a merge function cache.evict()removes a specific normalized entry;cache.gc()removes all unreachable entries- Custom keyFields must be stable and unique — using composite keys like ['orgId', 'userId'] is valid
Context
Apollo Client projects with mutations that should update existing cached data
Revisions (0)
No revisions yet.