Skip to content

patlux/react-query-cache-persistent

Repository files navigation

react-query-cache-persistent

This persistor extends QueryCache, enabling straightforward cache persistence without needing a hydration/dehydration phase. As a result, your app gains immediate access to data, eliminating loading states.

Its main performance benefit is storing queries individually rather than persisting the entire cache with each update. This significantly boosts performance when your cache size reaches several megabytes.

⚠️ However, this approach only supports synchronous operations. If your storage relies on asynchronous get/set methods, you won't be able to use this persistor.

Adapters

Create your own adapter

import { PersistentQueryCache } from 'react-query-cache-persistent'

// Your implementation. See below for examples.
const persistentQueryCache = new PersistentQueryCache({
  add: (query) => {
    // 1. use `query.queryHash` to query your store
    const queryState =
      /* from your store */
      // 2. assign the value from your store to `query.state`
      (query.state = queryState)

    // 3. write `query.state` into your store
  },
  updated: (query) => {
    // update your store
  },
  removed: (query) => {
    // remove `query.queryHash` from your store
  },
})

const queryClient = new QueryClient({ queryCache: persistentQueryCache })

Web

Uses localStorage as storage.

localStorage

import { PersistentQueryCache } from 'react-query-cache-persistent'

const persistentQueryCache = new PersistentQueryCache({
  add: (query) => {
    const item = window.localStorage.getItem(`queryCache.${query.queryHash}`)

    if (item != null) {
      query.state = JSON.parse(item)
    }

    window.localStorage.setItem(
      `queryCache.${query.queryHash}`,
      JSON.stringify(query.state),
    )
  },
  updated: (query) => {
    window.localStorage.setItem(
      `queryCache.${query.queryHash}`,
      JSON.stringify(query.state),
    )
  },
  removed: (query) => {
    window.localStorage.removeItem(`queryCache.${query.queryHash}`)
  },
})

const queryClient = new QueryClient({ queryCache: persistentQueryCache })

React Native

Uses @op-engineering/op-sqlite as storage. But you can use any sqlite solution as long it supports synchronous get/set.

The example below writes each query as a table row into a sqlite database

queryCache.sqlite3

License

MIT License.

About

Synchronous storage for tanstack query

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published