Skip to main content
Version: 2.2

useResource()

function useResource(fetchShape: ReadShape, params: object | null):
SchemaOf<typeof fetchShape.schema>;

function useResource(...[fetchShape: ReadShape, params: object | null]):
SchemaOf<typeof fetchShape.schema>[];
function useResource<
Params extends Readonly<object>,
Body extends Readonly<object | string> | void,
S extends Schema
>(fetchShape: ReadShape<S, Params, Body>, params: Params | null): SchemaOf<S>;

function useResource<
Params extends Readonly<object>,
Body extends Readonly<object | string> | void,
S extends Schema
>(...[fetchShape: ReadShape<S, Params, Body>, params: Params | null]): SchemaOf<S>[];

Rest Hooks 3.0 - Deprecation

This hook is being deprecated in favor of useResourceNew()

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

Excellent for retrieving the data you need.

Cache policy is Stale-While-Revalidate by default but also configurable.

  • Triggers fetch:
    • On first-render and when parameters change
    • and When not in cache or result is considered stale
    • and When no identical requests are in flight
    • and when params are not null
  • On Error (404, 500, etc):
  • While Loading:

Single

function Post({ id }: { id: number }) {
const post = useResource(PostResource.detailShape(), { id });
// post as PostResource
}

List

function Posts() {
const posts = useResource(PostResource.listShape(), {});
// posts as PostResource[]
}

Parallel

function Posts() {
const [user, posts] = useResource(
[UserResource.detailShape(), { id: userId }],
[PostResource.listShape(), { userId }],
);
// user as UserResource
// posts as PostResource[]
}

Sequential

function PostWithAuthor() {
const post = useResource(PostResource.detailShape(), { id });
// post as PostResource
const author = useResource(UserResource.detailShape(), {
id: post.userId,
});
// author as UserResource
}

Useful FetchShapes to send

Resource provides these built-in:

  • detailShape()
  • listShape()

Feel free to add your own FetchShape as well.