Skip to main content
Version: v7.0.0

useCache

Read the API Reference »

The useCache hook allows you to interact with the Cache of a given request. It provides state, methods, and event callbacks for cache changes. Ensure that the cacheKey is stable and not affected by auto-generation, so the hook always references the correct cache entry.

Purpose
  1. Easily manage and observe the cache for a specific request in React.
  2. Provides state and methods to interact with the cache layer.
  3. Enables the cache invalidation for refetching.

Quick Start

Just provide a prepared Request instance to the hook and listen to it's cache state.

Remember to match the cacheKey

Request's cacheKey are generated dynamically based on the request's queryKey and params. If you want to use useCache hook, you need to ensure that the cacheKey is matching the triggered request's cacheKey.

For example if your request has params, provide them like:

// When fetching data
const { data } = useFetch(getUser.setParams({ userId: 1 }));


// When listening to cache from another component
const { data } = useCache(getUser.setParams({ userId: 1 }));
import { useCache } from "@better-typed/react";

const { data, error, loading, invalidate, setData, setError, setLoading } = useCache(getUsers);

Invalidate cache

Invalidate the cache for the current request or a custom key.

const { invalidate } = useCache(request);

// Invalidate current request cache
invalidate();

// Invalidate by custom key (Regex or cacheKey)
invalidate(cacheKey);
Invalidating cache

In many cases, you don't need to use the useCache hook to invalidate cache entries. You can call the invalidate method directly on the cache instance for more flexibility. Do not worry - it is integrated with our hooks, so you can use it in the same way as with the useCache hook.

import { client } from "./client";

// Invalidate cache for a specific request
client.cache.invalidate(request);

// Invalidate cache by custom key (Regex or cacheKey)
client.cache.invalidate(/^getUsers/);

// Invalidate cache by request instance
client.cache.invalidate(request);

Options

Configuration options for this hook provided as a second parameter.

const { ... } = useCache(request, options)

UseCacheOptionsType
Name Type Description
deepCompare
boolean | typeof isEqual
Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
dependencyTracking
boolean
If true it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change.
initialResponse
CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>[data] | null
If cache is empty we can use placeholder data.


State and methods

This hook returns the following values.

const values = useCache(request);

useCache
Name Type Description
data
null | ExtractResponseType<T>
Request response data
error
null | ExtractErrorType<T>
Request response error
extra
null | ExtractAdapterExtraType<ExtractAdapterType<T>>
Request additional response data
loading
boolean
Request loading state
requestTimestamp
null | Date
Request response timestamp
responseTimestamp
null | Date
Request response timestamp
retries
number
Request attempts
status
null | ExtractAdapterStatusType<ExtractAdapterType<T>> | null
Request status
success
boolean
Information whether request succeeded
setData
(data: CacheSetState<ExtractResponseType<T> | null>) => void
Action to set custom data. We can do it locally(inside hook state). If you need to update cache data use client.cache.update(). method.
setError
(error: CacheSetState<ExtractErrorType<T> | null>) => void
Action to set custom error. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setExtra
(extra: CacheSetState<ExtractAdapterExtraType<ExtractAdapterType<T>> | null>) => void
Action to set custom additional data. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setLoading
(loading: CacheSetState<boolean>) => void
Action to set custom loading. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setRequestTimestamp
(timestamp: CacheSetState<Date>) => void
Action to set custom timestamp. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setResponseTimestamp
(timestamp: CacheSetState<Date>) => void
Action to set custom timestamp. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setRetries
(retries: CacheSetState<number>) => void
Action to set custom retries count. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
setStatus
(status: CacheSetState<ExtractAdapterStatusType<ExtractAdapterType<T>>>) => void
Action to set custom status. We can do it locally(inside hook state). If you need to turn on loading for all listening hooks use client.requestManager.events.emitLoading() method.
setSuccess
(success: CacheSetState<boolean>) => void
Action to set custom success. We can do it locally(inside hook state). If you need to update cache data use client.cache.update() method.
invalidate
(cacheKeys?: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => void
Invalidate cache for the current request or pass custom key to trigger it by invalidationKey(Regex / cacheKey).

useCache API Reference
Learn more about the useCache hook.

See also

Use with React
Overview of all React hooks and the approach to use them
Cache
Learn more about the Cache class and its methods