Skip to main content
Version: 2.2

useCache()

function useCache(
fetchShape: ReadShape,
params: object | null
): SchemaOf<typeof fetchShape.schema> | null;
function useCache<Params extends Readonly<object>, S extends Schema>(
{ schema, getFetchKey }: ReadShape<S, Params, any>,
params: Params | null
): SchemaOf<S> | null;

Rest Hooks 3.0 - Deprecation

This hook is being deprecated in favor of useCacheNew()

  • 3.0 this will be renamed to useCacheLegacy()
  • 3.1 will remove useCacheLegacy()

Excellent to use data in the normalized cache without fetching.

  • On Error (404, 500, etc):
    • Returns previously cached if exists
    • null otherwise
  • While loading:
    • Returns previously cached if exists
    • null otherwise

Example

Using a type guard to deal with null

function Post({ id }: { id: number }) {
const post = useCache(PostResource.detailShape(), { id });
// post as PostResource | null
if (!post) return null;
// post as PostResource (typeguarded)
// ...render stuff here
}

Useful FetchShapes to send

Resource provides these built-in:

  • detailShape()
  • listShape()

Feel free to add your own FetchShape as well.