or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-persistence.mdexperimental-features.mdindex.mdpersister-interface.mdreact-provider.md

core-persistence.mddocs/

0

# Core Persistence

1

2

Core persistence functions provide low-level control over cache restoration, saving, and subscription management. These functions are re-exported from `@tanstack/query-persist-client-core` for direct use when you need manual control over the persistence lifecycle.

3

4

## Capabilities

5

6

### persistQueryClient Function

7

8

High-level function that combines restoration and subscription into a single operation.

9

10

```typescript { .api }

11

/**

12

* Restores persisted data to QueryCache and persists further changes

13

* Combines restoration and subscription into a single operation

14

* @param props - Complete persistence configuration

15

* @returns Tuple of [unsubscribe function, restore promise]

16

*/

17

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

18

```

19

20

**Usage Example:**

21

22

```typescript

23

import { QueryClient } from '@tanstack/react-query';

24

import { persistQueryClient } from '@tanstack/react-query-persist-client';

25

26

const queryClient = new QueryClient();

27

28

const [unsubscribe, restorePromise] = persistQueryClient({

29

queryClient,

30

persister: myPersister,

31

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

32

buster: 'v1.0.0',

33

});

34

35

// Wait for restoration to complete

36

restorePromise

37

.then(() => console.log('Cache restored'))

38

.catch(() => console.log('Restoration failed'));

39

40

// Later, stop persistence

41

unsubscribe();

42

```

43

44

### persistQueryClientRestore Function

45

46

Restores persisted data to the QueryCache from the persister.

47

48

```typescript { .api }

49

/**

50

* Restores persisted data to the QueryCache

51

* Validates data age and buster string before restoration

52

* Automatically removes expired or invalid data

53

* @param options - Restoration configuration options

54

* @returns Promise that resolves when restoration completes

55

*/

56

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

57

```

58

59

**Usage Example:**

60

61

```typescript

62

import { persistQueryClientRestore } from '@tanstack/react-query-persist-client';

63

64

await persistQueryClientRestore({

65

queryClient,

66

persister: myPersister,

67

maxAge: 1000 * 60 * 60, // 1 hour

68

buster: 'v2.0.0', // invalidate caches from v1.x

69

hydrateOptions: {

70

// Control which queries get restored

71

shouldDehydrateQuery: (query) => query.queryKey[0] === 'user-data',

72

},

73

});

74

```

75

76

### persistQueryClientSave Function

77

78

Saves current QueryCache state to the persister.

79

80

```typescript { .api }

81

/**

82

* Persists current QueryCache data using the persister

83

* Dehydrates cache using provided options and saves with timestamp

84

* @param options - Save configuration options

85

* @returns Promise that resolves when save completes

86

*/

87

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

88

```

89

90

**Usage Example:**

91

92

```typescript

93

import { persistQueryClientSave } from '@tanstack/react-query-persist-client';

94

95

await persistQueryClientSave({

96

queryClient,

97

persister: myPersister,

98

buster: 'v1.0.0',

99

dehydrateOptions: {

100

// Only save successful queries

101

shouldDehydrateQuery: (query) => query.state.status === 'success',

102

// Don't save mutations

103

shouldDehydrateMutation: () => false,

104

},

105

});

106

```

107

108

### persistQueryClientSubscribe Function

109

110

Subscribes to QueryCache and MutationCache changes for automatic persistence.

111

112

```typescript { .api }

113

/**

114

* Subscribe to QueryCache and MutationCache changes for automatic persistence

115

* Triggers save operations when cache contents change

116

* @param props - Subscription configuration options

117

* @returns Unsubscribe function to stop monitoring

118

*/

119

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

120

```

121

122

**Usage Example:**

123

124

```typescript

125

import { persistQueryClientSubscribe } from '@tanstack/react-query-persist-client';

126

127

const unsubscribe = persistQueryClientSubscribe({

128

queryClient,

129

persister: myPersister,

130

buster: 'v1.0.0',

131

dehydrateOptions: {

132

shouldDehydrateQuery: (query) => {

133

// Only persist queries that have been successful for at least 5 minutes

134

const age = Date.now() - query.state.dataUpdatedAt;

135

return query.state.status === 'success' && age > 5 * 60 * 1000;

136

},

137

},

138

});

139

140

// Later, stop subscribing

141

unsubscribe();

142

```

143

144

## Advanced Usage Patterns

145

146

### Manual Cache Management

147

148

```typescript

149

import {

150

persistQueryClientRestore,

151

persistQueryClientSave,

152

persistQueryClientSubscribe

153

} from '@tanstack/react-query-persist-client';

154

155

class CacheManager {

156

private unsubscribe?: () => void;

157

158

async initialize() {

159

// Restore cache on app startup

160

await persistQueryClientRestore({

161

queryClient: this.queryClient,

162

persister: this.persister,

163

maxAge: this.config.maxAge,

164

});

165

166

// Start automatic persistence

167

this.startPersistence();

168

}

169

170

startPersistence() {

171

this.unsubscribe = persistQueryClientSubscribe({

172

queryClient: this.queryClient,

173

persister: this.persister,

174

dehydrateOptions: this.config.dehydrateOptions,

175

});

176

}

177

178

stopPersistence() {

179

this.unsubscribe?.();

180

this.unsubscribe = undefined;

181

}

182

183

async forceSave() {

184

await persistQueryClientSave({

185

queryClient: this.queryClient,

186

persister: this.persister,

187

dehydrateOptions: this.config.dehydrateOptions,

188

});

189

}

190

}

191

```

192

193

### Conditional Persistence

194

195

```typescript

196

// Only persist in certain conditions

197

const conditionalPersister = {

198

persistClient: async (client) => {

199

if (shouldPersist()) {

200

await actualPersister.persistClient(client);

201

}

202

},

203

restoreClient: () => actualPersister.restoreClient(),

204

removeClient: () => actualPersister.removeClient(),

205

};

206

207

function shouldPersist() {

208

return !window.navigator.userAgent.includes('Bot') &&

209

localStorage.getItem('persist-enabled') === 'true';

210

}

211

```

212

213

### Error Recovery

214

215

```typescript

216

async function robustRestore() {

217

try {

218

await persistQueryClientRestore({

219

queryClient,

220

persister: primaryPersister,

221

maxAge: 1000 * 60 * 60 * 24,

222

});

223

} catch (error) {

224

console.warn('Primary restore failed, trying backup');

225

try {

226

await persistQueryClientRestore({

227

queryClient,

228

persister: backupPersister,

229

maxAge: 1000 * 60 * 60 * 24,

230

});

231

} catch (backupError) {

232

console.warn('All restore attempts failed');

233

// Continue with fresh cache

234

}

235

}

236

}

237

```