Utilities for persisting TanStack Query cache data to various storage backends with restore functionality
npx @tessl/cli install tessl/npm-tanstack--query-persist-client-core@5.86.0A 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.
npm install @tanstack/query-persist-client-coreimport {
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");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();TanStack Query Persist Client Core is built around several key components:
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;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]>>;
}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;/** Default prefix for storage keys used in query persistence */
const PERSISTER_KEY_PREFIX = 'tanstack-query';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;
}