Custom hooks
A list of posts with a details panel where you can rename a post. The components never touch a request, a query param or
the cache. They call three hooks from hooks.ts: usePosts(), usePost(id) and useRenamePost(id).
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type Post = { id: number; title: string; body: string; userId: number };
export const getPostsRequest = client.createRequest<{
response: { posts: Post[]; total: number };
queryParams: { limit: number; select: string };
}>()({ endpoint: "/posts" });
export const getPostRequest = client.createRequest<{ response: Post }>()({
endpoint: "/posts/:postId",
});
export const updatePostRequest = client.createRequest<{
response: Post;
payload: Pick<Post, "title">;
}>()({
endpoint: "/posts/:postId",
method: "PATCH",
});
npx tiged BetterTyped/hyper-fetch/examples/react/custom-hooks hyper-fetch-react-custom-hooks && cd hyper-fetch-react-custom-hooks && npm install && npm run dev- Custom hooks wrap
useFetchanduseSubmit, so components ask for data in the words of the app. - Shared options live in one object next to the hooks, not in every component.
- Inferred types: the hooks return the typed
useFetchresult, sodata.postsis typed with no type in the component. - Side effects in one place:
useRenamePostupdates both cached copies of a post after a successful save.
How it works
-
api.tsdefines the client and three plain requests. It has no React code. -
hooks.tsfixes the details a component should not repeat.usePosts()always reads the same list, so the query params are set once:// `select` is a dummyjson query param: the API returns only these fields.const postsListRequest = getPostsRequest.setQueryParams({ limit: 5, select: "title,body,userId" });export const usePosts = () => useFetch(postsListRequest, sharedOptions);Every component that calls
usePosts()uses the same cache key, so they share one response. -
usePost(postId)sets the endpoint param. The hook returns theuseFetchresult as it is, sodata,error,loadingand the callbacks keep their types. -
useRenamePost(postId)returns{ renamePost, submitting, error }.renamePost(title)builds the payload and resolves with the response, so the form can checksuccess. InonSubmitSuccessthe hook writes the new title into the cached post and the cached list withclient.cache.update(), and both panels update. -
App.tsximports only fromhooks.ts. To change the page size, the options or the endpoint, you edit one file.
dummyjson does not store changes, so the new title lives only in the cache. With a real API you could call
client.cache.invalidate() in the hook instead and let the hooks refetch.
- A request used in more than one component.
- A mutation that has to update or invalidate other data after it succeeds.
- Keep a plain
useFetchcall for a one-off request on a single screen.
Related
Custom hooks put the request details, shared options and cache updates in one file. Components call usePosts() or
useRenamePost(id) and get fully typed results back.
