React Adapter
Learn how to use SoulCache with React
React Adapter
The React adapter provides hooks and components for seamless React integration.
Installation
Provider
Wrap your app with the provider:
Hooks
useQuery
Options:
| Option | Type | Default | Description |
|---|---|---|---|
queryKey | QueryKey | — | Cache identification key (required) |
queryFn | () => Promise<T> | — | Fetch function (required) |
enabled | boolean | true | Whether the query auto-fetches |
suspense | boolean | false | Throws a promise for React Suspense |
throwOnError | boolean | false | Throws the error for error boundaries |
onSuccess | (data: T) => void | — | Callback on successful fetch |
onError | (error: Error) => void | — | Callback on fetch error |
Returns:
| Property | Type | Description |
|---|---|---|
data | T | undefined | Current query data |
error | Error | null | Current error |
status | QueryStatus | 'idle' | 'loading' | 'success' | 'error' | 'fetching' |
fetchStatus | FetchStatus | 'idle' | 'fetching' | 'paused' |
isLoading | boolean | Loading with no data yet |
isFetching | boolean | Any fetch in progress |
isError | boolean | Error state |
isSuccess | boolean | Success state |
isIdle | boolean | Idle state |
dataUpdatedAt | number | Timestamp of last update |
useMutation
Options:
| Option | Type | Description |
|---|---|---|
mutationFn | (variables: TVariables) => Promise<TData> | The mutation function (required) |
onMutate | (variables: TVariables) => unknown | Pre-mutation callback (return context) |
onSuccess | (data, variables, context) => void | Post-success callback |
onError | (error, variables, context) => void | Post-error callback |
onSettled | (data, error, variables, context) => void | Post-settle callback |
Returns:
| Property | Type | Description |
|---|---|---|
data | TData | undefined | Mutation result data |
error | Error | null | Mutation error |
status | MutationStatus | 'idle' | 'pending' | 'success' | 'error' |
isPending | boolean | Currently executing |
isSuccess | boolean | Succeeded |
isError | boolean | Errored |
isIdle | boolean | Not yet triggered |
mutate | (variables: TVariables) => void | Trigger mutation |
mutateAsync | (variables: TVariables) => Promise<TData> | Trigger mutation (returns promise) |
reset | () => void | Reset mutation state |
useInfiniteQuery
useQueryClient
Access the QueryClient instance for imperative operations:
usePrefetchQuery
Returns a callback that silently prefetches data:
useIsFetching
Returns the count of currently fetching queries:
useIsMutating
Returns the count of currently pending mutations:
DevTools
Enable devtools for debugging:
Best Practices
React Guidelines
- Wrap once — Provider should be at the root of your app
- Stable keys — Don't create new arrays in render
- Error boundaries — Always wrap with error boundaries
- Cleanup — Provider handles cleanup automatically