Andrew Rhodes

Andrew Rhodes


Use apollo-cache-persist with React Native


Simple persistence for all Apollo Client 3.0 cache implementations, including InMemoryCache and Hermes.

Supports web and React Native. See all storage providers.

Basic Usage

To get started, simply pass your Apollo cache and an underlying storage provider to persistCache.

By default, the contents of your Apollo cache will be immediately restored (asynchronously, see how to persist data before rendering), and will be persisted upon every write to the cache (with a short debounce interval).


React Native
import AsyncStorage from '@react-native-community/async-storage';
import { InMemoryCache } from '@apollo/client/core';
import { persistCache } from 'apollo3-cache-persist';

const cache = new InMemoryCache({...});

// await before instantiating ApolloClient, else queries might run before the cache is persisted
await persistCache({
  storage: AsyncStorage,

// Continue setting up Apollo as usual.

const client = new ApolloClient({
import { InMemoryCache } from '@apollo/client/core';
import { persistCache } from 'apollo3-cache-persist';

const cache = new InMemoryCache({...});

// await before instantiating ApolloClient, else queries might run before the cache is persisted
await persistCache({
  storage: window.localStorage,

// Continue setting up Apollo as usual.

const client = new ApolloClient({

Additional Options

persistCache and the constructor for CachePersistor accept the following options:

   * Required options.

  // Reference to your Apollo cache.
  cache: ApolloCache<TSerialized>,

  // Reference to your storage provider.
  storage: PersistentStorage<TPersisted>,

   * Trigger options.

  // When to persist the cache.
  // 'write': Persist upon every write to the cache. Default.
  // 'background': Persist when your app moves to the background. React Native only.
  // For a custom trigger, provide a function. See below for more information.
  // To disable automatic persistence and manage persistence manually, provide false.
  trigger?: 'write' | 'background' | function | false,

  // Debounce interval between persists (in ms).
  // Defaults to 0 for 'background' and 1000 for 'write' and custom triggers.
  debounce?: number,

   * Storage options.

  // Key to use with the storage provider. Defaults to 'apollo-cache-persist'.
  key?: string,

  // Whether to serialize to JSON before/after persisting. Defaults to true.
  serialize?: boolean,

  // Maximum size of cache to persist (in bytes).
  // Defaults to 1048576 (1 MB). For unlimited cache size, provide false.
  // If exceeded, persistence will pause and app will start up cold on next launch.
  maxSize?: number | false,

   * Debugging options.

  // Enable console logging.
  debug?: boolean,

}): Promise<void>;

Advanced Usage

Using CachePersistor

Instead of using persistCache, you can instantiate a CachePersistor, which will give you fine-grained control of persistence.

CachePersistor accepts the same options as persistCache and returns an object with the following methods:

const persistor = new CachePersistor({...});

persistor.restore();   // Immediately restore the cache. Returns a Promise.
persistor.persist();   // Immediately persist the cache. Returns a Promise.
persistor.purge();     // Immediately purge the stored cache. Returns a Promise.

persistor.pause();     // Pause persistence. Triggers are ignored while paused.
persistor.resume();    // Resume persistence.
persistor.remove();    // Remove the persistence trigger. Manual persistence required after calling this.

// Obtain the most recent 30 persistor loglines.
// `print: true` will print them to the console; `false` will return an array.

// Obtain the current persisted cache size in bytes. Returns a Promise.
// Resolves to 0 for empty and `null` when `serialize: true` is in use.

Custom Triggers

For control over persistence timing, provide a function to the trigger option.

The custom trigger should accept one argument (a persist callback function), and it should return a function that can be called to uninstall the trigger.

The TypeScript signature for this function is as follows:

(persist: () => void) => (() => void)

For example, this custom trigger will persist every 10 seconds:

// This code is for illustration only.
// We do not recommend persisting on an interval.

const trigger = persist => {
  // Call `persist` every 10 seconds.
  const interval = setInterval(persist, 10000);

  // Return function to uninstall this custom trigger.
  return () => clearInterval(interval);

Storage Providers

The following storage providers work ‘out of the box’, with no additional dependencies:

  • AsyncStorage on React Native
  • window.localStorage on web
  • window.sessionStorage on web
  • localForage on web
  • Ionic storage on web and mobile

apollo3-cache-persist uses the same storage provider API as redux-persist, so you can also make use of the providers listed here, including:

If you’re using React Native and set a maxSize in excess of 2 MB, you must use a filesystem-based storage provider, such as redux-persist-fs-storage. AsyncStorage does not support individual values in excess of 2 MB on Android.

Common Questions

Why is the ‘background’ trigger only available for React Native?

Quite simply, because mobile apps are different than web apps.

Mobile apps are rarely terminated before transitioning to the background. This is helped by the fact that an app is moved to the background whenever the user returns home, activates the multitasking view, or follows a link to another app. There’s almost always an opportunity to persist.

On web, we could support a ‘background’ trigger with the Page Visibility API; however, data would be lost if the user closed the tab/window directly. Given this prevalence of this user behavior and the substantially better performance of the ‘write’ trigger on web, we’ve omitted a ‘background’ trigger on web.

How do I wait for the cache to be restored before rendering my app?

persistCache (as well as persistor.restore()) returns a promise that will resolve once the cache has been restored, which you can await before rendering your app.

This library, like Apollo Client, is framework agnostic; however, since many people have asked, here’s an example of how to handle this in React. PRs with examples from other frameworks are welcome.

import React, { Component } from 'react';
import { ApolloProvider } from '@apollo/client/react';
import { InMemoryCache } from '@apollo/client/core';
import { persistCache } from 'apollo3-cache-persist';

class App extends Component {
  state = {
    client: null,
    loaded: false,

  async componentDidMount() {
    const cache = new InMemoryCache({...});

    // Setup your Apollo Link, and any other Apollo packages here.

    const client = new ApolloClient({

    try {
      // See above for additional options, including other storage providers.
      await persistCache({
        storage: window.localStorage,
    } catch (error) {
      console.error('Error restoring Apollo cache', error);

      loaded: true,

  render() {
    const { client, loaded } = this.state;

    if (!loaded) {
      return <div>Loading...</div>;

    return (
      <ApolloProvider client={client}>
        {/* the rest of your app goes here */}
React Using Hooks
import React,{ useState, useEffect } from 'react';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from '@apollo/client/core';
import { ApolloProvider } from "@apollo/react-hooks"
import { persistCache } from 'apollo3-cache-persist';

const App: React.FC = () => {
  const [client, setClient] = useState(undefined);
  useEffect(() => {
    const cache = new InMemoryCache({...});

    const client = new ApolloClient({
    const initData = {
      {/* your initial data */}
    cache.writeData({ data: initData })

    // See above for additional options, including other storage providers.
      storage: window.localStorage
    }).then(() => {
      client.onResetStore(async () => cache.writeData({ data: initData }));
    return () => {};
  }, []);
  if (client === undefined) return <div>Loading...</div>;
  return (
    <ApolloProvider client={client}>
      {/* the rest of your app goes here */}
export default App;
Using Synchronous Storage API

persistCache method is asynchronous to conform to production ready storage interfaces which offer only asynchronous API.

apollo-cache-persist offers alternative persistCacheSync method that should be used only with small cache sizes and synchronous storage provider (e.g. window.localStorage). persistCacheSync is best suited for demo applications because it blocks UI rendering until the cache is restored.

import { InMemoryCache } from '@apollo/client/core';
import { persistCacheSync } from 'apollo3-cache-persist';

const cache = new InMemoryCache({...});

    storage: window.localStorage,

persistCacheSync works by instantiating subclasses of CachePeristor, Persistor, and Storage that implement a method for restoring the cache synchronously.

I need to ensure certain data is not persisted. How do I filter my cache?

Unfortunately, this is not yet possible. You can only persist and restore the cache in its entirety.

This library depends upon the extract and persist methods defined upon the cache interface in Apollo Client 2.0. The payload returned and consumed by these methods is opaque and differs from cache to cache. As such, we cannot reliably transform the output.

Alternatives have been recommended in #2, including using logic in your UI to filter potentially-outdated information. Furthermore, the maxSize option and methods on CachePersistor provide facilities to manage the growth of the cache.

For total control over the cache contents, you can setup a background task to periodically reset the cache to contain only your app’s most important data. (On the web, you can use a service worker; on React Native, there’s react-native-background-task.) The background task would start with an empty cache, query the most important data from your GraphQL API, and then persist. This strategy has the added benefit of ensuring the cache is loaded with fresh data when your app launches.

Finally, it’s worth mentioning that the Apollo community is in the early stages of designing fine-grained cache controls, including the ability to utilize directives and metadata to control cache policy on a per-key basis, so the answer to this question will eventually change.

I’ve had a breaking schema change. How do I migrate or purge my cache?

For the same reasons given in the preceding answer, it’s not possible to migrate or transform your persisted cache data. However, by using the methods on CachePersistor, it’s simple to reset the cache upon changes to the schema.

Simply instantiate a CachePersistor and only call restore() if the app’s schema hasn’t change. (You’ll need to track your schema version yourself.)

Here’s an example of how this could look:

import AsyncStorage from '@react-native-community/async-storage';
import { InMemoryCache } from '@apollo/client/core';
import { CachePersistor } from 'apollo3-cache-persist';

const SCHEMA_VERSION = '3'; // Must be a string.
const SCHEMA_VERSION_KEY = 'apollo-schema-version';

async function setupApollo() {
  const cache = new InMemoryCache({...});

  const persistor = new CachePersistor({
    storage: AsyncStorage,

  // Read the current schema version from AsyncStorage.
  const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY);

  if (currentVersion === SCHEMA_VERSION) {
    // If the current version matches the latest version,
    // we're good to go and can restore the cache.
    await persistor.restore();
  } else {
    // Otherwise, we'll want to purge the outdated persisted cache
    // and mark ourselves as having updated to the latest version.
    await persistor.purge();
    await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION);

  // Continue setting up Apollo as usual.
I’m seeing errors on Android.

Specifically, this error:

BaseError: Couldn't read row 0, col 0 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

This is the result of a 2 MB per key limitation of AsyncStorage on Android. Set a smaller maxSize or switch to a different storage provider, such as redux-persist-fs-storage or react-native-mmkv-storage.

Cache persist and changing user context

In some cases like user logout we want to wipe out application cache. To do it effectively with Apollo Cache Persist please use client.clearStore() method that will eventually reset persistence layer.

Download Details:

Author: apollographql

Source Code:

#react-native #react #mobile-apps

What is GEEK

Buddha Community

Use apollo-cache-persist with React Native
Autumn  Blick

Autumn Blick


How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms?

React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. Hire Dedicated React Native Developer from top React Native development company, to design a spectacular React Native application for your business.

Consult with experts:-

#hire dedicated react native developer #react native development company #react native development services #react native development #react native developer #react native

Hire Dedicated React Native Developers - WebClues Infotech

Being one of the emerging frameworks for app development the need to develop react native apps has increased over the years.

Looking for a react native developer?

Worry not! WebClues infotech offers services to Hire React Native Developers for your app development needs. We at WebClues Infotech offer a wide range of Web & Mobile App Development services based o your business or Startup requirement for Android and iOS apps.

WebClues Infotech also has a flexible method of cost calculation for hiring react native developers such as Hourly, Weekly, or Project Basis.

Want to get your app idea into reality with a react native framework?

Get in touch with us.

Hire React Native Developer Now:

For inquiry:


#hire react native developers #hire dedicated react native developers #hire react native developer #hiring a react native developer #hire freelance react native developers #hire react native developers in 1 hour

Factors affecting the cost of hiring a React Native developer in USA -

Want to develop app using React Native? Here are the tips that will help to reduce the cost of react native app development for you.
Cost is a major factor in helping entrepreneurs take decisions about investing in developing an app and the decision to hire react native app developers in USA can prove to be fruitful in the long run. Using react native for app development ensures a wide range of benefits to your business. Understanding your business and working on the aspects to strengthen business processes through a cost-efficient mobile app will be the key to success.

#best react native development companies from the us #top react native app development companies in usa #cost of hiring a react native developer in usa #top-notch react native developer in usa #best react native developers usa #react native

How much does it cost to develop a React Native mobile app?

React Native allows developers to develop mobile apps that have compatibility with Android, iOS & other operating systems. Due to the features like Native-like functionality and single code reusability and the access of various frameworks in the market, React Native has excelled as the most suitable framework for cross-platform mobile app development.

Why Do Businesses Prefer React Native App Development?

React Native is integrated with JS library that works as the fundamental for developing the app UI. Most businesses choose for developing React Native apps just due to their cross-platform & open-source features. A few further reasons why entrepreneurs & developers choose React Native app development include:

• Lowered Expedition Time

• Simple UI

• Cross-Platform and Code Sharing

• Lesser Workforce and Resources

• Community Assistance

• In-Built Elements and Reusable Codes

• Hot Reload

• JavaScript as Programming Language

• Easy to Execute Updates

Factors That Decide Cost of React Native App Development

If you are an entrepreneur or start-up and looking for cost-effective app development, React Native is one of the ideal options available out there.

• App’s UI/UX Design

• User Authorization

• App Complexity and Functionality

• App Development Team

• App Maintenance

• App Add-ons

• App Distribution

• Location of Development Company

• App Category

React Native cost depends widely on the complexity of a project or the app requirements. The price may also vary based on business requirements. React Native app development per hour can cost from $20 and $30 per hour in India. It can vary as per different locations.

Is React Native a good choice for mobile apps development?

Yes, React Native is the best choice for mobile app development as React apps are faster to develop and it offers better quality than hybrid apps. Additionally, React Native is a mature cross-platform framework.

Best React Native App Development Agency

AppClues Infotech is a leading React Native App Development Company in USA that build robust & innovative mobile app as per your specific business needs. They have a dedicated team of designers and programmers help to make a perfect mobile app.

If you have any mobile app development project in mind get in touch with AppClues Infotech and get the best solution for your business.

#react native app development cost #react native development company #best react native development company in usa #hire react native developers #hire dedicated react native developers & programmers #hire a react native development company