or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-persistence.mdindex.mdquery-persistence.mdretry-strategies.md
tile.json

tessl/npm-tanstack--query-persist-client-core

Utilities for persisting TanStack Query cache data to various storage backends with restore functionality

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@tanstack/query-persist-client-core@5.86.x

To install, run

npx @tessl/cli install tessl/npm-tanstack--query-persist-client-core@5.86.0

index.mddocs/

TanStack Query Persist Client Core

A comprehensive TypeScript library providing utilities for persisting TanStack Query (React Query) cache data to various storage backends and restoring it later. This enables applications to maintain query cache state across browser sessions, app restarts, or navigation, improving user experience by reducing loading times and network requests.

Package Information

  • Package Name: @tanstack/query-persist-client-core
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @tanstack/query-persist-client-core

Core Imports

import {
  persistQueryClient,
  persistQueryClientRestore,
  persistQueryClientSave,
  persistQueryClientSubscribe,
  experimental_createQueryPersister,
  removeOldestQuery,
  PERSISTER_KEY_PREFIX,
  type Persister,
  type PersistedClient,
  type PersistQueryClientOptions,
  type PersistedQueryClientRestoreOptions,
  type PersistedQueryClientSaveOptions,
  type PersistQueryClientRootOptions,
  type StoragePersisterOptions,
  type AsyncStorage,
  type PersistedQuery,
  type PersistRetryer,
  type MaybePromise,
  type Promisable
} from "@tanstack/query-persist-client-core";

For CommonJS:

const {
  persistQueryClient,
  persistQueryClientRestore,
  persistQueryClientSave,
  persistQueryClientSubscribe,
  experimental_createQueryPersister,
  removeOldestQuery,
  PERSISTER_KEY_PREFIX
} = require("@tanstack/query-persist-client-core");

Basic Usage

import { QueryClient } from "@tanstack/query-core";
import { persistQueryClient } from "@tanstack/query-persist-client-core";

// Create a QueryClient
const queryClient = new QueryClient();

// Create a simple persister using localStorage
const persister = {
  persistClient: async (client) => {
    localStorage.setItem("queryClient", JSON.stringify(client));
  },
  restoreClient: async () => {
    const stored = localStorage.getItem("queryClient");
    return stored ? JSON.parse(stored) : undefined;
  },
  removeClient: async () => {
    localStorage.removeItem("queryClient");
  }
};

// Set up persistence with automatic restore and ongoing saves
const [unsubscribe, restorePromise] = persistQueryClient({
  queryClient,
  persister,
  buster: "v1.0", // Cache-busting string
  maxAge: 1000 * 60 * 60 * 24, // 24 hours
});

// Wait for initial restore to complete
await restorePromise;

// Later, when cleanup is needed
unsubscribe();

Architecture

TanStack Query Persist Client Core is built around several key components:

  • Persister Interface: A simple async storage contract that can be implemented for any storage backend
  • Client-level Persistence: Complete query client state management with automatic dehydration/hydration
  • Fine-grained Persistence: Query-by-query persistence for selective caching (experimental)
  • Retry Strategies: Configurable fallback mechanisms when persistence fails due to storage limits
  • Cache Management: Built-in expiration, cache-busting, and garbage collection features

Capabilities

Client-Level Persistence

Complete query client persistence system that automatically saves and restores entire query cache state. Perfect for maintaining application state across sessions.

function persistQueryClient(
  props: PersistQueryClientOptions
): [() => void, Promise<void>];

function persistQueryClientRestore(
  options: PersistedQueryClientRestoreOptions
): Promise<void>;

function persistQueryClientSave(
  options: PersistedQueryClientSaveOptions
): Promise<void>;

function persistQueryClientSubscribe(
  props: PersistedQueryClientSaveOptions
): () => void;

Client-Level Persistence

Fine-Grained Query Persistence

Experimental feature providing query-by-query persistence with selective restoration and advanced storage management. Ideal for applications requiring granular control over cached data.

function experimental_createQueryPersister<TStorageValue = string>(
  options: StoragePersisterOptions<TStorageValue>
): QueryPersisterObject;

interface QueryPersisterObject {
  persisterFn: <T, TQueryKey extends QueryKey>(
    queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,
    ctx: QueryFunctionContext<TQueryKey>,
    query: Query
  ) => Promise<T>;
  persistQuery: (query: Query) => Promise<void>;
  persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
  retrieveQuery: <T>(
    queryHash: string,
    afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void
  ) => Promise<T | undefined>;
  persisterGc: () => Promise<void>;
  restoreQueries: (
    queryClient: QueryClient,
    filters?: Pick<QueryFilters, 'queryKey' | 'exact'>
  ) => Promise<void>;
}

interface AsyncStorage<TStorageValue = string> {
  getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>;
  setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>;
  removeItem: (key: string) => MaybePromise<void>;
  entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>;
}

Fine-Grained Persistence

Retry Strategies

Configurable retry mechanisms for handling persistence failures due to storage quotas or other constraints. Provides built-in strategies and supports custom implementations.

type PersistRetryer = (props: {
  persistedClient: PersistedClient;
  error: Error;
  errorCount: number;
}) => PersistedClient | undefined;

const removeOldestQuery: PersistRetryer;

Retry Strategies

Constants

/** Default prefix for storage keys used in query persistence */
const PERSISTER_KEY_PREFIX = 'tanstack-query';

Core Types

interface Persister {
  persistClient: (persistClient: PersistedClient) => Promisable<void>;
  restoreClient: () => Promisable<PersistedClient | undefined>;
  removeClient: () => Promisable<void>;
}

interface PersistedClient {
  timestamp: number;
  buster: string;
  clientState: DehydratedState;
}

interface PersistQueryClientOptions
  extends PersistedQueryClientRestoreOptions,
    PersistedQueryClientSaveOptions,
    PersistQueryClientRootOptions {}

interface PersistedQueryClientRestoreOptions
  extends PersistQueryClientRootOptions {
  maxAge?: number;
  hydrateOptions?: HydrateOptions;
}

interface PersistedQueryClientSaveOptions
  extends PersistQueryClientRootOptions {
  dehydrateOptions?: DehydrateOptions;
}

interface PersistQueryClientRootOptions {
  queryClient: QueryClient;
  persister: Persister;
  buster?: string;
}

type Promisable<T> = T | PromiseLike<T>;

type MaybePromise<T> = T | Promise<T>;

interface StoragePersisterOptions<TStorageValue = string> {
  storage: AsyncStorage<TStorageValue> | undefined | null;
  serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>;
  deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>;
  buster?: string;
  maxAge?: number;
  prefix?: string;
  filters?: QueryFilters;
}

interface PersistedQuery {
  buster: string;
  queryHash: string;
  queryKey: QueryKey;
  state: QueryState;
}