or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# TanStack Query Persist Client Core

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @tanstack/query-persist-client-core

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @tanstack/query-persist-client-core`

10

11

## Core Imports

12

13

```typescript

14

import {

15

persistQueryClient,

16

persistQueryClientRestore,

17

persistQueryClientSave,

18

persistQueryClientSubscribe,

19

experimental_createQueryPersister,

20

removeOldestQuery,

21

PERSISTER_KEY_PREFIX,

22

type Persister,

23

type PersistedClient,

24

type PersistQueryClientOptions,

25

type PersistedQueryClientRestoreOptions,

26

type PersistedQueryClientSaveOptions,

27

type PersistQueryClientRootOptions,

28

type StoragePersisterOptions,

29

type AsyncStorage,

30

type PersistedQuery,

31

type PersistRetryer,

32

type MaybePromise,

33

type Promisable

34

} from "@tanstack/query-persist-client-core";

35

```

36

37

For CommonJS:

38

39

```javascript

40

const {

41

persistQueryClient,

42

persistQueryClientRestore,

43

persistQueryClientSave,

44

persistQueryClientSubscribe,

45

experimental_createQueryPersister,

46

removeOldestQuery,

47

PERSISTER_KEY_PREFIX

48

} = require("@tanstack/query-persist-client-core");

49

```

50

51

## Basic Usage

52

53

```typescript

54

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

55

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

56

57

// Create a QueryClient

58

const queryClient = new QueryClient();

59

60

// Create a simple persister using localStorage

61

const persister = {

62

persistClient: async (client) => {

63

localStorage.setItem("queryClient", JSON.stringify(client));

64

},

65

restoreClient: async () => {

66

const stored = localStorage.getItem("queryClient");

67

return stored ? JSON.parse(stored) : undefined;

68

},

69

removeClient: async () => {

70

localStorage.removeItem("queryClient");

71

}

72

};

73

74

// Set up persistence with automatic restore and ongoing saves

75

const [unsubscribe, restorePromise] = persistQueryClient({

76

queryClient,

77

persister,

78

buster: "v1.0", // Cache-busting string

79

maxAge: 1000 * 60 * 60 * 24, // 24 hours

80

});

81

82

// Wait for initial restore to complete

83

await restorePromise;

84

85

// Later, when cleanup is needed

86

unsubscribe();

87

```

88

89

## Architecture

90

91

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

92

93

- **Persister Interface**: A simple async storage contract that can be implemented for any storage backend

94

- **Client-level Persistence**: Complete query client state management with automatic dehydration/hydration

95

- **Fine-grained Persistence**: Query-by-query persistence for selective caching (experimental)

96

- **Retry Strategies**: Configurable fallback mechanisms when persistence fails due to storage limits

97

- **Cache Management**: Built-in expiration, cache-busting, and garbage collection features

98

99

## Capabilities

100

101

### Client-Level Persistence

102

103

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

104

105

```typescript { .api }

106

function persistQueryClient(

107

props: PersistQueryClientOptions

108

): [() => void, Promise<void>];

109

110

function persistQueryClientRestore(

111

options: PersistedQueryClientRestoreOptions

112

): Promise<void>;

113

114

function persistQueryClientSave(

115

options: PersistedQueryClientSaveOptions

116

): Promise<void>;

117

118

function persistQueryClientSubscribe(

119

props: PersistedQueryClientSaveOptions

120

): () => void;

121

```

122

123

[Client-Level Persistence](./client-persistence.md)

124

125

### Fine-Grained Query Persistence

126

127

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

128

129

```typescript { .api }

130

function experimental_createQueryPersister<TStorageValue = string>(

131

options: StoragePersisterOptions<TStorageValue>

132

): QueryPersisterObject;

133

134

interface QueryPersisterObject {

135

persisterFn: <T, TQueryKey extends QueryKey>(

136

queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,

137

ctx: QueryFunctionContext<TQueryKey>,

138

query: Query

139

) => Promise<T>;

140

persistQuery: (query: Query) => Promise<void>;

141

persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;

142

retrieveQuery: <T>(

143

queryHash: string,

144

afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void

145

) => Promise<T | undefined>;

146

persisterGc: () => Promise<void>;

147

restoreQueries: (

148

queryClient: QueryClient,

149

filters?: Pick<QueryFilters, 'queryKey' | 'exact'>

150

) => Promise<void>;

151

}

152

153

interface AsyncStorage<TStorageValue = string> {

154

getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>;

155

setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>;

156

removeItem: (key: string) => MaybePromise<void>;

157

entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>;

158

}

159

```

160

161

[Fine-Grained Persistence](./query-persistence.md)

162

163

### Retry Strategies

164

165

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

166

167

```typescript { .api }

168

type PersistRetryer = (props: {

169

persistedClient: PersistedClient;

170

error: Error;

171

errorCount: number;

172

}) => PersistedClient | undefined;

173

174

const removeOldestQuery: PersistRetryer;

175

```

176

177

[Retry Strategies](./retry-strategies.md)

178

179

## Constants

180

181

```typescript { .api }

182

/** Default prefix for storage keys used in query persistence */

183

const PERSISTER_KEY_PREFIX = 'tanstack-query';

184

```

185

186

## Core Types

187

188

```typescript { .api }

189

interface Persister {

190

persistClient: (persistClient: PersistedClient) => Promisable<void>;

191

restoreClient: () => Promisable<PersistedClient | undefined>;

192

removeClient: () => Promisable<void>;

193

}

194

195

interface PersistedClient {

196

timestamp: number;

197

buster: string;

198

clientState: DehydratedState;

199

}

200

201

interface PersistQueryClientOptions

202

extends PersistedQueryClientRestoreOptions,

203

PersistedQueryClientSaveOptions,

204

PersistQueryClientRootOptions {}

205

206

interface PersistedQueryClientRestoreOptions

207

extends PersistQueryClientRootOptions {

208

maxAge?: number;

209

hydrateOptions?: HydrateOptions;

210

}

211

212

interface PersistedQueryClientSaveOptions

213

extends PersistQueryClientRootOptions {

214

dehydrateOptions?: DehydrateOptions;

215

}

216

217

interface PersistQueryClientRootOptions {

218

queryClient: QueryClient;

219

persister: Persister;

220

buster?: string;

221

}

222

223

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

224

225

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

226

227

interface StoragePersisterOptions<TStorageValue = string> {

228

storage: AsyncStorage<TStorageValue> | undefined | null;

229

serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>;

230

deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>;

231

buster?: string;

232

maxAge?: number;

233

prefix?: string;

234

filters?: QueryFilters;

235

}

236

237

interface PersistedQuery {

238

buster: string;

239

queryHash: string;

240

queryKey: QueryKey;

241

state: QueryState;

242

}

243

```