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

react-provider.mddocs/

0

# React Provider

1

2

The PersistQueryClientProvider component provides React-specific persistence capabilities by wrapping the standard QueryClientProvider with automatic cache restoration and persistence subscription.

3

4

## Capabilities

5

6

### PersistQueryClientProvider Component

7

8

Main React provider component that manages the complete persistence lifecycle for React Query cache.

9

10

```typescript { .api }

11

/**

12

* React provider component that wraps QueryClientProvider to add persistence capabilities

13

* Automatically restores cache on mount and subscribes to changes for continuous persistence

14

* @param props - Component props including persist options and callbacks

15

* @returns JSX element providing persistence context

16

*/

17

function PersistQueryClientProvider(props: PersistQueryClientProviderProps): React.JSX.Element;

18

19

interface PersistQueryClientProviderProps extends QueryClientProviderProps {

20

/** Persistence configuration options (queryClient is automatically provided) */

21

persistOptions: OmitKeyof<PersistQueryClientOptions, 'queryClient'>;

22

/** Optional callback executed after successful cache restoration */

23

onSuccess?: () => Promise<unknown> | unknown;

24

/** Optional callback executed after failed cache restoration */

25

onError?: () => Promise<unknown> | unknown;

26

}

27

```

28

29

**Usage Examples:**

30

31

```typescript

32

import React from 'react';

33

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

34

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

35

36

const queryClient = new QueryClient();

37

38

// Basic usage

39

function App() {

40

return (

41

<PersistQueryClientProvider

42

client={queryClient}

43

persistOptions={{ persister: myPersister }}

44

>

45

<MyAppComponents />

46

</PersistQueryClientProvider>

47

);

48

}

49

50

// With success/error handling

51

function AppWithCallbacks() {

52

const handleRestoreSuccess = () => {

53

console.log('Query cache restored successfully');

54

// Optional: trigger app-specific logic after restoration

55

};

56

57

const handleRestoreError = () => {

58

console.error('Failed to restore query cache');

59

// Optional: show user notification or fallback behavior

60

};

61

62

return (

63

<PersistQueryClientProvider

64

client={queryClient}

65

persistOptions={{

66

persister: myPersister,

67

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

68

buster: 'v1.0.0' // invalidate old caches

69

}}

70

onSuccess={handleRestoreSuccess}

71

onError={handleRestoreError}

72

>

73

<MyAppComponents />

74

</PersistQueryClientProvider>

75

);

76

}

77

78

// With custom hydration options

79

function AppWithHydrationOptions() {

80

return (

81

<PersistQueryClientProvider

82

client={queryClient}

83

persistOptions={{

84

persister: myPersister,

85

hydrateOptions: {

86

// Only restore queries, not mutations

87

shouldDehydrateQuery: () => true,

88

shouldDehydrateMutation: () => false,

89

},

90

dehydrateOptions: {

91

// Custom dehydration settings for persistence

92

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

93

}

94

}}

95

>

96

<MyAppComponents />

97

</PersistQueryClientProvider>

98

);

99

}

100

```

101

102

### Provider Behavior

103

104

The component follows this lifecycle:

105

106

1. **Mount**: Sets isRestoring state to `true`

107

2. **Restoration**: Calls `persistQueryClientRestore` with provided options

108

3. **Success/Error**: Executes appropriate callback and sets isRestoring to `false`

109

4. **Subscription**: After successful restoration, subscribes to cache changes for continuous persistence

110

5. **Unmount**: Automatically unsubscribes from cache changes

111

112

### IsRestoring Context

113

114

The provider uses `IsRestoringProvider` from `@tanstack/react-query` to communicate restoration state to child components.

115

116

```typescript

117

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

118

119

function MyComponent() {

120

const isRestoring = useIsRestoring();

121

122

if (isRestoring) {

123

return <div>Loading cached data...</div>;

124

}

125

126

return <div>App content</div>;

127

}

128

```

129

130

### Client Switching

131

132

The provider handles QueryClient changes correctly:

133

134

```typescript

135

function AppWithClientSwitching() {

136

const [client, setClient] = useState(() => new QueryClient());

137

138

// When client changes, provider will:

139

// 1. Unsubscribe from old client

140

// 2. Restore cache in new client (if not already done)

141

// 3. Subscribe to new client changes

142

143

return (

144

<PersistQueryClientProvider

145

client={client}

146

persistOptions={{ persister: myPersister }}

147

>

148

<button onClick={() => setClient(new QueryClient())}>

149

Switch Client

150

</button>

151

<MyAppComponents />

152

</PersistQueryClientProvider>

153

);

154

}

155

```

156

157

### Error Handling

158

159

When restoration fails:

160

161

1. The persister's `removeClient()` method is called to clean up invalid data

162

2. The `onError` callback is executed (if provided)

163

3. A warning is logged in development mode

164

4. The restoration process continues normally (queries will fetch fresh data)

165

166

### StrictMode Compatibility

167

168

The component is designed to work correctly in React StrictMode without duplicate restoration attempts or subscriptions.