React Router
A contacts app built on the React Router data router. Every route has a loader that fills the HyperFetch cache before
the route renders, so the components read their data with useFetch and never show a loading state. An edit form saves
through a route action. A small panel lists the requests that reach the network, so you can see which navigations were
served from the cache.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createBrowserRouter, RouterProvider } from "react-router";
import { EditUser, editAction, Home, Root, RouteError, rootLoader, UserPage, userLoader } from "./routes";
const router = createBrowserRouter([
{
path: "/",
loader: rootLoader,
Component: Root,
children: [
{ index: true, Component: Home },
{
path: "users/:userId",
loader: userLoader,
errorElement: <RouteError />,
children: [
{ index: true, Component: UserPage },
{ path: "edit", Component: EditUser, action: editAction },
],
},
],
},
]);
export const App = () => <RouterProvider router={router} />;
npx tiged BetterTyped/hyper-fetch/examples/react/react-router hyper-fetch-react-react-router && cd hyper-fetch-react-react-router && npm install && npm run dev- Loaders prefetch with
send({ cachePolicy: "cache-first" }): cached data returns at once, new data is fetched. - Components read the cache with
useFetch(request, { revalidate: false }), built by the same function as in the loader. - Search in the URL: the search form changes
?q=, the loader runs again, and each query has its own cache entry. - An action sends the
PUT, writes the answer into the cache withclient.cache.update()and redirects.
How it works
-
src/api.tsdefines the requests with a 30 secondstaleTimeand exportsuserList(q)anduserDetails(userId). The loaders and the components call these functions, so they always build the same cache key. -
src/App.tsxcreates the router withcreateBrowserRouter. The root route lists users,users/:userIdshows one, andusers/:userId/editholds the form with itsaction. -
rootLoaderreadsqfrom the URL and awaits the list;userLoaderdoes the same for one user:const response = await userDetails(userId).send({cachePolicy: "cache-first",});if (response.status === 404) throw data("User not found", { status: 404 });React Router waits for the loader, so the page renders with the data already in the cache.
-
Root,UserPageandEditUsercalluseFetch(..., { revalidate: false }). The data is fresh, so the hooks send nothing. Once it is older thanstaleTime, the hook refreshes it in the background. -
Open a user, open another, then go back to the first. The network panel shows two
GET /users/:userIdrequests, not three. The panel comes fromclient.onRequest, which runs for every request that is sent. -
editActionreads the form, sendsupdateUser.setParams({ userId }).send({ payload }), and on success callsclient.cache.update(userDetails(userId), ...)with the saved user beforeredirect(). The user page reads the new name from the cache. dummyjson does not store edits, so the list keeps the old name; with a real API, invalidate the list in the action as well.
- Apps on the React Router data router that want caching, deduplication and retries for their loader data.
- Pages that should render without spinners after navigation, and render instantly when you come back.
- Forms handled by route actions that should update the data other routes show.
Related
Loaders call send({ cachePolicy: "cache-first" }) to fill the cache, and components read the same requests with
useFetch. Actions send mutations and update the cache, so React Router owns navigation and HyperFetch owns the data.
