Published in


How to Update Relay Cache

Photo by Alina Grubnyak on Unsplash

What Relay Cache Looks Like

Relay stores its cache as a graph of records. Each record is identified by its unique ID, and a record can have scalar fields and “links” to other records.

  1. Access it directly by its ID.
  2. Access the user which is linked to the Post record of our interest, then follow the link.

How to Update Relay Cache

There are two ways to update Relay cache.

  1. Fetch the updated record from server.
  2. Use Relay updater function.

Approach 1: Fetch the Updated Record

The first approach is easier and cleaner. If server can response with the updated record after mutation, Relay can automatically update the cache accordingly. Look at this GraphQL mutation:

Approach 2: Updater Function

Receiving the updated value immediately as a response is nice, but sometimes we cannot change APIs to suit our needs. This is where we need to manually modify Relay cache using updater function. I will cover the basics in this article, but you might want to check out Relay’s official documentation on this topic.

  • getValue : Gets the value of a scalar field.
  • setValue : Sets the value of a scalar field.
  • getLinkedRecord : If a field is linked to another record, get RecordProxy of the linked record.
  • setLinkedRecord : Link the given field to the given record. If there is an existing linked record, the original linked record is unlinked.
  • getLinkedRecords : gets a list of linked records (e.g. User.posts ).

Alternatives to Cache Update

Maybe your issue can be resolved without updating Relay cache. Consider these alternatives before writing your updater function.

Cache Invalidation

We can invalidate individual records using RecordProxy.invalidateRecord method. Calling this method will mark the Record as “stale” and force Relay not to re-use this cached record. Note that invalidation does not trigger any refetch unless specified inside useSubscribeToInvalidationState hook.

Imperative Refetch

Relay provides for fetchQuery and useQueryLoader for imperative usage. We can trigger imperative re-fetch on mutation completion.


If server can respond to mutation with the updated record, let Relay use server response to update its cache. When server response is insufficient, we can read & write pretty much any value inside Relay cache using updater function as long as we know how to locate the records of our interest.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store