react-router 7.16.0 → 7.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -1
- package/dist/development/{browser-nIQ4Nsyi.d.mts → browser-CGcs-0pD.d.mts} +1 -1
- package/dist/development/{chunk-QUQL4437.mjs → chunk-6CSD65Y2.mjs} +2 -2
- package/dist/{production/chunk-NALGHHKE.mjs → development/chunk-ASILSGTR.mjs} +2 -2
- package/dist/development/{chunk-SRID2YZ2.js → chunk-KFNXW4AL.js} +1 -1
- package/dist/development/{chunk-XEJDWL2B.js → chunk-PBLBZ3QU.js} +7 -7
- package/dist/{production/chunk-SKEDDLRM.js → development/chunk-PULC7NLK.js} +99 -99
- package/dist/development/{context-m8rizgnE.d.mts → context-CmHpk1Ws.d.mts} +1 -1
- package/dist/development/dom-export.d.mts +3 -3
- package/dist/development/dom-export.d.ts +1 -1
- package/dist/development/dom-export.js +28 -28
- package/dist/development/dom-export.mjs +3 -3
- package/dist/development/{index-react-server-client-BLiUx67a.d.ts → index-react-server-client-CwU9bE5R.d.ts} +1 -1
- package/dist/development/{index-react-server-client-CdKROblb.d.mts → index-react-server-client-DPrDrCew.d.mts} +1 -1
- package/dist/development/index-react-server-client.d.mts +2 -2
- package/dist/development/index-react-server-client.d.ts +1 -1
- package/dist/development/index-react-server-client.js +4 -4
- package/dist/development/index-react-server-client.mjs +2 -2
- package/dist/development/index-react-server.js +1 -1
- package/dist/development/index-react-server.mjs +1 -1
- package/dist/development/index.d.mts +6 -6
- package/dist/development/index.d.ts +2 -2
- package/dist/development/index.js +85 -85
- package/dist/development/index.mjs +3 -3
- package/dist/development/lib/types/internal.js +1 -1
- package/dist/development/lib/types/internal.mjs +1 -1
- package/dist/production/{browser-nIQ4Nsyi.d.mts → browser-CGcs-0pD.d.mts} +1 -1
- package/dist/{development/chunk-S54KXAEJ.mjs → production/chunk-5TQZEVD5.mjs} +2 -2
- package/dist/production/{chunk-EAQNHM3N.js → chunk-CTIXC7EV.js} +7 -7
- package/dist/{development/chunk-IBI7OMNB.js → production/chunk-EN242BO4.js} +99 -99
- package/dist/production/{chunk-Q65P7S7Y.mjs → chunk-OSYEOCBT.mjs} +2 -2
- package/dist/production/{chunk-Y7DNFQZP.js → chunk-RTRY3JFT.js} +1 -1
- package/dist/production/{context-m8rizgnE.d.mts → context-CmHpk1Ws.d.mts} +1 -1
- package/dist/production/dom-export.d.mts +3 -3
- package/dist/production/dom-export.d.ts +1 -1
- package/dist/production/dom-export.js +28 -28
- package/dist/production/dom-export.mjs +3 -3
- package/dist/production/{index-react-server-client-BLiUx67a.d.ts → index-react-server-client-CwU9bE5R.d.ts} +1 -1
- package/dist/production/{index-react-server-client-CdKROblb.d.mts → index-react-server-client-DPrDrCew.d.mts} +1 -1
- package/dist/production/index-react-server-client.d.mts +2 -2
- package/dist/production/index-react-server-client.d.ts +1 -1
- package/dist/production/index-react-server-client.js +4 -4
- package/dist/production/index-react-server-client.mjs +2 -2
- package/dist/production/index-react-server.js +1 -1
- package/dist/production/index-react-server.mjs +1 -1
- package/dist/production/index.d.mts +6 -6
- package/dist/production/index.d.ts +2 -2
- package/dist/production/index.js +85 -85
- package/dist/production/index.mjs +3 -3
- package/dist/production/lib/types/internal.js +1 -1
- package/dist/production/lib/types/internal.mjs +1 -1
- package/docs/explanation/backend-for-frontend.md +50 -0
- package/docs/explanation/code-splitting.md +61 -0
- package/docs/explanation/concurrency.md +135 -0
- package/docs/explanation/form-vs-fetcher.md +292 -0
- package/docs/explanation/hot-module-replacement.md +137 -0
- package/docs/explanation/hydration.md +14 -0
- package/docs/explanation/index-query-param.md +86 -0
- package/docs/explanation/index.md +4 -0
- package/docs/explanation/lazy-route-discovery.md +78 -0
- package/docs/explanation/location.md +6 -0
- package/docs/explanation/progressive-enhancement.md +150 -0
- package/docs/explanation/race-conditions.md +88 -0
- package/docs/explanation/react-transitions.md +160 -0
- package/docs/explanation/route-matching.md +7 -0
- package/docs/explanation/server-client-execution.md +4 -0
- package/docs/explanation/sessions-and-cookies.md +465 -0
- package/docs/explanation/special-files.md +16 -0
- package/docs/explanation/state-management.md +524 -0
- package/docs/explanation/styling.md +87 -0
- package/docs/explanation/type-safety.md +82 -0
- package/docs/how-to/accessibility.md +44 -0
- package/docs/how-to/client-data.md +199 -0
- package/docs/how-to/data-strategy.md +317 -0
- package/docs/how-to/error-boundary.md +231 -0
- package/docs/how-to/error-reporting.md +142 -0
- package/docs/how-to/fetchers.md +307 -0
- package/docs/how-to/file-route-conventions.md +410 -0
- package/docs/how-to/file-uploads.md +217 -0
- package/docs/how-to/form-validation.md +120 -0
- package/docs/how-to/headers.md +164 -0
- package/docs/how-to/index.md +4 -0
- package/docs/how-to/instrumentation.md +556 -0
- package/docs/how-to/meta.md +40 -0
- package/docs/how-to/middleware.md +763 -0
- package/docs/how-to/navigation-blocking.md +233 -0
- package/docs/how-to/optimize-revalidation.md +12 -0
- package/docs/how-to/pre-rendering.md +225 -0
- package/docs/how-to/presets.md +103 -0
- package/docs/how-to/react-server-components.md +899 -0
- package/docs/how-to/resource-routes.md +126 -0
- package/docs/how-to/route-module-type-safety.md +100 -0
- package/docs/how-to/search-params.md +4 -0
- package/docs/how-to/security.md +30 -0
- package/docs/how-to/server-bundles.md +66 -0
- package/docs/how-to/spa.md +120 -0
- package/docs/how-to/status.md +63 -0
- package/docs/how-to/suspense.md +132 -0
- package/docs/how-to/using-handle.md +117 -0
- package/docs/how-to/view-transitions.md +237 -0
- package/docs/how-to/webhook.md +50 -0
- package/docs/index.md +39 -0
- package/docs/start/data/actions.md +138 -0
- package/docs/start/data/custom.md +198 -0
- package/docs/start/data/data-loading.md +44 -0
- package/docs/start/data/index.md +4 -0
- package/docs/start/data/installation.md +52 -0
- package/docs/start/data/navigating.md +12 -0
- package/docs/start/data/pending-ui.md +12 -0
- package/docs/start/data/route-object.md +268 -0
- package/docs/start/data/routing.md +281 -0
- package/docs/start/data/testing.md +8 -0
- package/docs/start/declarative/index.md +4 -0
- package/docs/start/declarative/installation.md +43 -0
- package/docs/start/declarative/navigating.md +133 -0
- package/docs/start/declarative/routing.md +237 -0
- package/docs/start/declarative/url-values.md +65 -0
- package/docs/start/framework/actions.md +174 -0
- package/docs/start/framework/data-loading.md +201 -0
- package/docs/start/framework/deploying.md +96 -0
- package/docs/start/framework/index.md +4 -0
- package/docs/start/framework/installation.md +41 -0
- package/docs/start/framework/navigating.md +182 -0
- package/docs/start/framework/pending-ui.md +142 -0
- package/docs/start/framework/rendering.md +59 -0
- package/docs/start/framework/route-module.md +527 -0
- package/docs/start/framework/routing.md +362 -0
- package/docs/start/framework/testing.md +133 -0
- package/docs/start/index.md +4 -0
- package/docs/start/modes.md +201 -0
- package/docs/upgrading/component-routes.md +363 -0
- package/docs/upgrading/future.md +280 -0
- package/docs/upgrading/index.md +4 -0
- package/docs/upgrading/remix.md +403 -0
- package/docs/upgrading/router-provider.md +442 -0
- package/docs/upgrading/v6.md +382 -0
- package/package.json +2 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* react-router v7.
|
|
2
|
+
* react-router v7.17.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Remix Software Inc.
|
|
5
5
|
*
|
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
isSession,
|
|
29
29
|
routeRSCServerRequest,
|
|
30
30
|
setDevServerHooks
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-5TQZEVD5.mjs";
|
|
32
32
|
import {
|
|
33
33
|
Action,
|
|
34
34
|
Await,
|
|
@@ -142,7 +142,7 @@ import {
|
|
|
142
142
|
withComponentProps,
|
|
143
143
|
withErrorBoundaryProps,
|
|
144
144
|
withHydrateFallbackProps
|
|
145
|
-
} from "./chunk-
|
|
145
|
+
} from "./chunk-OSYEOCBT.mjs";
|
|
146
146
|
export {
|
|
147
147
|
Await,
|
|
148
148
|
BrowserRouter,
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Backend For Frontend
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Backend For Frontend
|
|
6
|
+
|
|
7
|
+
[MODES: framework]
|
|
8
|
+
|
|
9
|
+
<br/>
|
|
10
|
+
<br/>
|
|
11
|
+
|
|
12
|
+
While React Router can serve as your fullstack application, it also fits perfectly into the "Backend for Frontend" architecture.
|
|
13
|
+
|
|
14
|
+
The BFF strategy employs a web server with a job scoped to serving the frontend web app and connecting it to the services it needs: your database, mailer, job queues, existing backend APIs (REST, GraphQL), etc. Instead of your UI integrating directly from the browser to these services, it connects to the BFF, and the BFF connects to your services.
|
|
15
|
+
|
|
16
|
+
Mature apps already have a lot of backend application code in Ruby, Elixir, PHP, etc., and there's no reason to justify migrating it all to a server-side JavaScript runtime just to get the benefits of React Router. Instead, you can use your React Router app as a backend for your frontend.
|
|
17
|
+
|
|
18
|
+
You can use `fetch` right from your loaders and actions to your backend.
|
|
19
|
+
|
|
20
|
+
```tsx lines=[7,13,17]
|
|
21
|
+
import escapeHtml from "escape-html";
|
|
22
|
+
|
|
23
|
+
export async function loader() {
|
|
24
|
+
const apiUrl = "https://api.example.com/some-data.json";
|
|
25
|
+
const res = await fetch(apiUrl, {
|
|
26
|
+
headers: {
|
|
27
|
+
Authorization: `Bearer ${process.env.API_TOKEN}`,
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const data = await res.json();
|
|
32
|
+
|
|
33
|
+
const prunedData = data.map((record) => {
|
|
34
|
+
return {
|
|
35
|
+
id: record.id,
|
|
36
|
+
title: record.title,
|
|
37
|
+
formattedBody: escapeHtml(record.content),
|
|
38
|
+
};
|
|
39
|
+
});
|
|
40
|
+
return { prunedData };
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
There are several benefits of this approach vs. fetching directly from the browser. The highlighted lines above show how you can:
|
|
45
|
+
|
|
46
|
+
1. Simplify third-party integrations and keep tokens and secrets out of client bundles
|
|
47
|
+
2. Prune the data down to send less kB over the network, speeding up your app significantly
|
|
48
|
+
3. Move a lot of code from browser bundles to the server, like `escapeHtml`, which speeds up your app. Additionally, moving code to the server usually makes your code easier to maintain since server-side code doesn't have to worry about UI states for async operations
|
|
49
|
+
|
|
50
|
+
Again, React Router can be used as your only server by talking directly to the database and other services with server-side JavaScript APIs, but it also works perfectly as a backend for your frontend. Go ahead and keep your existing API server for application logic and let React Router connect the UI to it.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Automatic Code Splitting
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Automatic Code Splitting
|
|
6
|
+
|
|
7
|
+
[MODES: framework]
|
|
8
|
+
|
|
9
|
+
<br/>
|
|
10
|
+
<br/>
|
|
11
|
+
|
|
12
|
+
When using React Router's framework features, your application is automatically code split to improve the performance of initial load times when users visit your application.
|
|
13
|
+
|
|
14
|
+
## Code Splitting by Route
|
|
15
|
+
|
|
16
|
+
Consider this simple route config:
|
|
17
|
+
|
|
18
|
+
```tsx filename=app/routes.ts
|
|
19
|
+
import {
|
|
20
|
+
type RouteConfig,
|
|
21
|
+
route,
|
|
22
|
+
} from "@react-router/dev/routes";
|
|
23
|
+
|
|
24
|
+
export default [
|
|
25
|
+
route("/contact", "./contact.tsx"),
|
|
26
|
+
route("/about", "./about.tsx"),
|
|
27
|
+
] satisfies RouteConfig;
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Instead of bundling all routes into a single giant build, the modules referenced (`contact.tsx` and `about.tsx`) become entry points to the bundler.
|
|
31
|
+
|
|
32
|
+
Because these entry points are coupled to URL segments, React Router knows just from a URL which bundles are needed in the browser, and more importantly, which are not.
|
|
33
|
+
|
|
34
|
+
If the user visits `"/about"` then the bundles for `about.tsx` will be loaded but not `contact.tsx`. This drastically reduces the JavaScript footprint for initial page loads and speeds up your application.
|
|
35
|
+
|
|
36
|
+
## Removal of Server Code
|
|
37
|
+
|
|
38
|
+
Any server-only [Route Module APIs][route-module] will be removed from the bundles. Consider this route module:
|
|
39
|
+
|
|
40
|
+
```tsx
|
|
41
|
+
export async function loader() {
|
|
42
|
+
return { message: "hello" };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function action() {
|
|
46
|
+
console.log(Date.now());
|
|
47
|
+
return { ok: true };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function headers() {
|
|
51
|
+
return { "Cache-Control": "max-age=300" };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export default function Component({ loaderData }) {
|
|
55
|
+
return <div>{loaderData.message}</div>;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
After building for the browser, only the `Component` will still be in the bundle, so you can use server-only code in the other module exports.
|
|
60
|
+
|
|
61
|
+
[route-module]: ../start/framework/route-module
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Network Concurrency Management
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Network Concurrency Management
|
|
6
|
+
|
|
7
|
+
[MODES: framework, data]
|
|
8
|
+
|
|
9
|
+
<br/>
|
|
10
|
+
<br/>
|
|
11
|
+
|
|
12
|
+
When building web applications, managing network requests can be a daunting task. The challenges of ensuring up-to-date data and handling simultaneous requests often lead to complex logic in the application to deal with interruptions and race conditions. React Router simplifies this process by automating network management while mirroring and expanding upon the intuitive behavior of web browsers.
|
|
13
|
+
|
|
14
|
+
To help understand how React Router handles concurrency, it's important to remember that after `form` submissions, React Router will fetch fresh data from the `loader`s. This is called revalidation.
|
|
15
|
+
|
|
16
|
+
## Natural Alignment with Browser Behavior
|
|
17
|
+
|
|
18
|
+
React Router's handling of network concurrency is heavily inspired by the default behavior of web browsers when processing documents.
|
|
19
|
+
|
|
20
|
+
### Link Navigation
|
|
21
|
+
|
|
22
|
+
**Browser Behavior**: When you click on a link in a browser and then click on another before the page transition completes, the browser prioritizes the most recent `action`. It cancels the initial request, focusing solely on the latest link clicked.
|
|
23
|
+
|
|
24
|
+
**React Router Behavior**: React Router manages client-side navigation the same way. When a link is clicked within a React Router application, it initiates fetch requests for each `loader` tied to the target URL. If another navigation interrupts the initial navigation, React Router cancels the previous fetch requests, ensuring that only the latest requests proceed.
|
|
25
|
+
|
|
26
|
+
### Form Submission
|
|
27
|
+
|
|
28
|
+
**Browser Behavior**: If you initiate a form submission in a browser and then quickly submit another form again, the browser disregards the first submission, processing only the latest one.
|
|
29
|
+
|
|
30
|
+
**React Router Behavior**: React Router mimics this behavior when working with forms. If a form is submitted and another submission occurs before the first completes, React Router cancels the original fetch requests. It then waits for the latest submission to complete before triggering page revalidation again.
|
|
31
|
+
|
|
32
|
+
## Concurrent Submissions and Revalidation
|
|
33
|
+
|
|
34
|
+
While standard browsers are limited to one request at a time for navigations and form submissions, React Router elevates this behavior. Unlike navigation, with [`useFetcher`][use_fetcher] multiple requests can be in flight simultaneously.
|
|
35
|
+
|
|
36
|
+
React Router is designed to handle multiple form submissions to server `action`s and concurrent revalidation requests efficiently. It ensures that as soon as new data is available, the state is updated promptly. However, React Router also safeguards against potential pitfalls by refraining from committing stale data when other `action`s introduce race conditions.
|
|
37
|
+
|
|
38
|
+
For instance, if three form submissions are in progress, and one completes, React Router updates the UI with that data immediately without waiting for the other two so that the UI remains responsive and dynamic. As the remaining submissions finalize, React Router continues to update the UI, ensuring that the most recent data is displayed.
|
|
39
|
+
|
|
40
|
+
Using this key:
|
|
41
|
+
|
|
42
|
+
- `|`: Submission begins
|
|
43
|
+
- ✓: Action complete, data revalidation begins
|
|
44
|
+
- ✅: Revalidated data is committed to the UI
|
|
45
|
+
- ❌: Request cancelled
|
|
46
|
+
|
|
47
|
+
We can visualize this scenario in the following diagram:
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
submission 1: |----✓-----✅
|
|
51
|
+
submission 2: |-----✓-----✅
|
|
52
|
+
submission 3: |-----✓-----✅
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
However, if a subsequent submission's revalidation completes before an earlier one, React Router discards the earlier data, ensuring that only the most up-to-date information is reflected in the UI:
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
submission 1: |----✓---------❌
|
|
59
|
+
submission 2: |-----✓-----✅
|
|
60
|
+
submission 3: |-----✓-----✅
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Because the revalidation from submission (2) started later and landed earlier than submission (1), the requests from submission (1) are canceled and only the data from submission (2) is committed to the UI. It was requested later, so it's more likely to contain the updated values from both (1) and (2).
|
|
64
|
+
|
|
65
|
+
## Potential for Stale Data
|
|
66
|
+
|
|
67
|
+
It's unlikely your users will ever experience this, but there are still chances for the user to see stale data in very rare conditions with inconsistent infrastructure. Even though React Router cancels requests for stale data, they will still end up making it to the server. Canceling a request in the browser simply releases browser resources for that request; it can't "catch up" and stop it from getting to the server. In extremely rare conditions, a canceled request may change data after the interrupting `action`'s revalidation lands. Consider this diagram:
|
|
68
|
+
|
|
69
|
+
```text
|
|
70
|
+
👇 interruption with new submission
|
|
71
|
+
|----❌----------------------✓
|
|
72
|
+
|-------✓-----✅
|
|
73
|
+
👆
|
|
74
|
+
initial request reaches the server
|
|
75
|
+
after the interrupting submission
|
|
76
|
+
has completed revalidation
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The user is now looking at different data than what is on the server. Note that this problem is both extremely rare and exists with default browser behavior, too. The chance of the initial request reaching the server later than both the submission and revalidation of the second is unexpected on any network and server infrastructure. If this is a concern with your infrastructure, you can send timestamps with your form submissions and write server logic to ignore stale submissions.
|
|
80
|
+
|
|
81
|
+
## Example
|
|
82
|
+
|
|
83
|
+
In UI components like comboboxes, each keystroke can trigger a network request. Managing such rapid, consecutive requests can be tricky, especially when ensuring that the displayed results match the most recent query. However, with React Router, this challenge is automatically handled, ensuring that users see the correct results without developers having to micromanage the network.
|
|
84
|
+
|
|
85
|
+
```tsx filename=app/pages/city-search.tsx
|
|
86
|
+
export async function loader({ request }) {
|
|
87
|
+
const { searchParams } = new URL(request.url);
|
|
88
|
+
const cities = await searchCities(searchParams.get("q"));
|
|
89
|
+
return cities;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function CitySearchCombobox() {
|
|
93
|
+
const fetcher = useFetcher<typeof loader>();
|
|
94
|
+
|
|
95
|
+
return (
|
|
96
|
+
<fetcher.Form action="/city-search">
|
|
97
|
+
<Combobox aria-label="Cities">
|
|
98
|
+
<ComboboxInput
|
|
99
|
+
name="q"
|
|
100
|
+
onChange={(event) =>
|
|
101
|
+
// submit the form onChange to get the list of cities
|
|
102
|
+
fetcher.submit(event.target.form)
|
|
103
|
+
}
|
|
104
|
+
/>
|
|
105
|
+
|
|
106
|
+
{/* render with the loader's data */}
|
|
107
|
+
{fetcher.data ? (
|
|
108
|
+
<ComboboxPopover className="shadow-popup">
|
|
109
|
+
{fetcher.data.length > 0 ? (
|
|
110
|
+
<ComboboxList>
|
|
111
|
+
{fetcher.data.map((city) => (
|
|
112
|
+
<ComboboxOption
|
|
113
|
+
key={city.id}
|
|
114
|
+
value={city.name}
|
|
115
|
+
/>
|
|
116
|
+
))}
|
|
117
|
+
</ComboboxList>
|
|
118
|
+
) : (
|
|
119
|
+
<span>No results found</span>
|
|
120
|
+
)}
|
|
121
|
+
</ComboboxPopover>
|
|
122
|
+
) : null}
|
|
123
|
+
</Combobox>
|
|
124
|
+
</fetcher.Form>
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
All the application needs to know is how to query the data and how to render it. React Router handles the network.
|
|
130
|
+
|
|
131
|
+
## Conclusion
|
|
132
|
+
|
|
133
|
+
React Router offers developers an intuitive, browser-based approach to managing network requests. By mirroring browser behaviors and enhancing them where needed, it simplifies the complexities of concurrency, revalidation, and potential race conditions. Whether you're building a simple webpage or a sophisticated web application, React Router ensures that your user interactions are smooth, reliable, and always up to date.
|
|
134
|
+
|
|
135
|
+
[use_fetcher]: ../api/hooks/useFetcher
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Form vs. fetcher
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Form vs. fetcher
|
|
6
|
+
|
|
7
|
+
[MODES: framework, data]
|
|
8
|
+
|
|
9
|
+
## Overview
|
|
10
|
+
|
|
11
|
+
Developing in React Router offers a rich set of tools that can sometimes overlap in functionality, creating a sense of ambiguity for newcomers. The key to effective development in React Router is understanding the nuances and appropriate use cases for each tool. This document seeks to provide clarity on when and why to use specific APIs.
|
|
12
|
+
|
|
13
|
+
## APIs in Focus
|
|
14
|
+
|
|
15
|
+
- [`<Form>`][form-component]
|
|
16
|
+
- [`useFetcher`][use-fetcher]
|
|
17
|
+
- [`useNavigation`][use-navigation]
|
|
18
|
+
|
|
19
|
+
Understanding the distinctions and intersections of these APIs is vital for efficient and effective React Router development.
|
|
20
|
+
|
|
21
|
+
## URL Considerations
|
|
22
|
+
|
|
23
|
+
The primary criterion when choosing among these tools is whether you want the URL to change or not:
|
|
24
|
+
|
|
25
|
+
- **URL Change Desired**: When navigating or transitioning between pages, or after certain actions like creating or deleting records. This ensures that the user's browser history accurately reflects their journey through your application.
|
|
26
|
+
- **Expected Behavior**: In many cases, when users hit the back button, they should be taken to the previous page. Other times the history entry may be replaced but the URL change is important nonetheless.
|
|
27
|
+
|
|
28
|
+
- **No URL Change Desired**: For actions that don't significantly change the context or primary content of the current view. This might include updating individual fields or minor data manipulations that don't warrant a new URL or page reload. This also applies to loading data with fetchers for things like popovers, combo boxes, etc.
|
|
29
|
+
|
|
30
|
+
### When the URL Should Change
|
|
31
|
+
|
|
32
|
+
These actions typically reflect significant changes to the user's context or state:
|
|
33
|
+
|
|
34
|
+
- **Creating a New Record**: After creating a new record, it's common to redirect users to a page dedicated to that new record, where they can view or further modify it.
|
|
35
|
+
|
|
36
|
+
- **Deleting a Record**: If a user is on a page dedicated to a specific record and decides to delete it, the logical next step is to redirect them to a general page, such as a list of all records.
|
|
37
|
+
|
|
38
|
+
For these cases, developers should consider using a combination of [`<Form>`][form-component] and [`useNavigation`][use-navigation]. These tools can be coordinated to handle form submission, invoke specific actions, retrieve action-related data through component props, and manage navigation respectively.
|
|
39
|
+
|
|
40
|
+
### When the URL Shouldn't Change
|
|
41
|
+
|
|
42
|
+
These actions are generally more subtle and don't require a context switch for the user:
|
|
43
|
+
|
|
44
|
+
- **Updating a Single Field**: Maybe a user wants to change the name of an item in a list or update a specific property of a record. This action is minor and doesn't necessitate a new page or URL.
|
|
45
|
+
|
|
46
|
+
- **Deleting a Record from a List**: In a list view, if a user deletes an item, they likely expect to remain on the list view, with that item no longer in the list.
|
|
47
|
+
|
|
48
|
+
- **Creating a Record in a List View**: When adding a new item to a list, it often makes sense for the user to remain in that context, seeing their new item added to the list without a full page transition.
|
|
49
|
+
|
|
50
|
+
- **Loading Data for a Popover or Combobox**: When loading data for a popover or combobox, the user's context remains unchanged. The data is loaded in the background and displayed in a small, self-contained UI element.
|
|
51
|
+
|
|
52
|
+
For such actions, [`useFetcher`][use-fetcher] is the go-to API. It's versatile, combining functionalities of these APIs, and is perfectly suited for tasks where the URL should remain unchanged.
|
|
53
|
+
|
|
54
|
+
## API Comparison
|
|
55
|
+
|
|
56
|
+
As you can see, the two sets of APIs have a lot of similarities:
|
|
57
|
+
|
|
58
|
+
| Navigation/URL API | Fetcher API |
|
|
59
|
+
| ----------------------------- | -------------------- |
|
|
60
|
+
| `<Form>` | `<fetcher.Form>` |
|
|
61
|
+
| `actionData` (component prop) | `fetcher.data` |
|
|
62
|
+
| `navigation.state` | `fetcher.state` |
|
|
63
|
+
| `navigation.formAction` | `fetcher.formAction` |
|
|
64
|
+
| `navigation.formData` | `fetcher.formData` |
|
|
65
|
+
|
|
66
|
+
## Examples
|
|
67
|
+
|
|
68
|
+
### Creating a New Record
|
|
69
|
+
|
|
70
|
+
```tsx filename=app/pages/new-recipe.tsx lines=[16,23-24,29]
|
|
71
|
+
import {
|
|
72
|
+
Form,
|
|
73
|
+
redirect,
|
|
74
|
+
useNavigation,
|
|
75
|
+
} from "react-router";
|
|
76
|
+
import type { Route } from "./+types/new-recipe";
|
|
77
|
+
|
|
78
|
+
export async function action({
|
|
79
|
+
request,
|
|
80
|
+
}: Route.ActionArgs) {
|
|
81
|
+
const formData = await request.formData();
|
|
82
|
+
const errors = await validateRecipeFormData(formData);
|
|
83
|
+
if (errors) {
|
|
84
|
+
return { errors };
|
|
85
|
+
}
|
|
86
|
+
const recipe = await db.recipes.create(formData);
|
|
87
|
+
return redirect(`/recipes/${recipe.id}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function NewRecipe({
|
|
91
|
+
actionData,
|
|
92
|
+
}: Route.ComponentProps) {
|
|
93
|
+
const { errors } = actionData || {};
|
|
94
|
+
const navigation = useNavigation();
|
|
95
|
+
const isSubmitting =
|
|
96
|
+
navigation.formAction === "/recipes/new";
|
|
97
|
+
|
|
98
|
+
return (
|
|
99
|
+
<Form method="post">
|
|
100
|
+
<label>
|
|
101
|
+
Title: <input name="title" />
|
|
102
|
+
{errors?.title ? <span>{errors.title}</span> : null}
|
|
103
|
+
</label>
|
|
104
|
+
<label>
|
|
105
|
+
Ingredients: <textarea name="ingredients" />
|
|
106
|
+
{errors?.ingredients ? (
|
|
107
|
+
<span>{errors.ingredients}</span>
|
|
108
|
+
) : null}
|
|
109
|
+
</label>
|
|
110
|
+
<label>
|
|
111
|
+
Directions: <textarea name="directions" />
|
|
112
|
+
{errors?.directions ? (
|
|
113
|
+
<span>{errors.directions}</span>
|
|
114
|
+
) : null}
|
|
115
|
+
</label>
|
|
116
|
+
<button type="submit">
|
|
117
|
+
{isSubmitting ? "Saving..." : "Create Recipe"}
|
|
118
|
+
</button>
|
|
119
|
+
</Form>
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The example leverages [`<Form>`][form-component], component props, and [`useNavigation`][use-navigation] to facilitate an intuitive record creation process.
|
|
125
|
+
|
|
126
|
+
Using `<Form>` ensures direct and logical navigation. After creating a record, the user is naturally guided to the new recipe's unique URL, reinforcing the outcome of their action.
|
|
127
|
+
|
|
128
|
+
The component props bridge server and client, providing immediate feedback on submission issues. This quick response enables users to rectify any errors without hindrance.
|
|
129
|
+
|
|
130
|
+
Lastly, `useNavigation` dynamically reflects the form's submission state. This subtle UI change, like toggling the button's label, assures users that their actions are being processed.
|
|
131
|
+
|
|
132
|
+
Combined, these APIs offer a balanced blend of structured navigation and feedback.
|
|
133
|
+
|
|
134
|
+
### Updating a Record
|
|
135
|
+
|
|
136
|
+
Now consider we're looking at a list of recipes that have delete buttons on each item. When a user clicks the delete button, we want to delete the recipe from the database and remove it from the list without navigating away from the list.
|
|
137
|
+
|
|
138
|
+
First, consider the basic route setup to get a list of recipes on the page:
|
|
139
|
+
|
|
140
|
+
```tsx filename=app/pages/recipes.tsx
|
|
141
|
+
import type { Route } from "./+types/recipes";
|
|
142
|
+
|
|
143
|
+
export async function loader({
|
|
144
|
+
request,
|
|
145
|
+
}: Route.LoaderArgs) {
|
|
146
|
+
return {
|
|
147
|
+
recipes: await db.recipes.findAll({ limit: 30 }),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export default function Recipes({
|
|
152
|
+
loaderData,
|
|
153
|
+
}: Route.ComponentProps) {
|
|
154
|
+
const { recipes } = loaderData;
|
|
155
|
+
return (
|
|
156
|
+
<ul>
|
|
157
|
+
{recipes.map((recipe) => (
|
|
158
|
+
<RecipeListItem key={recipe.id} recipe={recipe} />
|
|
159
|
+
))}
|
|
160
|
+
</ul>
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Now we'll look at the action that deletes a recipe and the component that renders each recipe in the list.
|
|
166
|
+
|
|
167
|
+
```tsx filename=app/pages/recipes.tsx lines=[10,21,27]
|
|
168
|
+
import { useFetcher } from "react-router";
|
|
169
|
+
import type { Recipe } from "./recipe.server";
|
|
170
|
+
import type { Route } from "./+types/recipes";
|
|
171
|
+
|
|
172
|
+
export async function action({
|
|
173
|
+
request,
|
|
174
|
+
}: Route.ActionArgs) {
|
|
175
|
+
const formData = await request.formData();
|
|
176
|
+
const id = formData.get("id");
|
|
177
|
+
await db.recipes.delete(id);
|
|
178
|
+
return { ok: true };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export default function Recipes() {
|
|
182
|
+
return (
|
|
183
|
+
// ...
|
|
184
|
+
// doesn't matter, somewhere it's using <RecipeListItem />
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function RecipeListItem({ recipe }: { recipe: Recipe }) {
|
|
189
|
+
const fetcher = useFetcher();
|
|
190
|
+
const isDeleting = fetcher.state !== "idle";
|
|
191
|
+
|
|
192
|
+
return (
|
|
193
|
+
<li>
|
|
194
|
+
<h2>{recipe.title}</h2>
|
|
195
|
+
<fetcher.Form method="post">
|
|
196
|
+
<input type="hidden" name="id" value={recipe.id} />
|
|
197
|
+
<button disabled={isDeleting} type="submit">
|
|
198
|
+
{isDeleting ? "Deleting..." : "Delete"}
|
|
199
|
+
</button>
|
|
200
|
+
</fetcher.Form>
|
|
201
|
+
</li>
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Using [`useFetcher`][use-fetcher] in this scenario works perfectly. Instead of navigating away or refreshing the entire page, we want in-place updates. When a user deletes a recipe, the `action` is called and the fetcher manages the corresponding state transitions.
|
|
207
|
+
|
|
208
|
+
The key advantage here is the maintenance of context. The user stays on the list when the deletion completes. The fetcher's state management capabilities are leveraged to give real-time feedback: it toggles between `"Deleting..."` and `"Delete"`, providing a clear indication of the ongoing process.
|
|
209
|
+
|
|
210
|
+
Furthermore, with each `fetcher` having the autonomy to manage its own state, operations on individual list items become independent, ensuring that actions on one item don't affect the others (though revalidation of the page data is a shared concern covered in [Network Concurrency Management][network-concurrency-management]).
|
|
211
|
+
|
|
212
|
+
In essence, `useFetcher` offers a seamless mechanism for actions that don't necessitate a change in the URL or navigation, enhancing the user experience by providing real-time feedback and context preservation.
|
|
213
|
+
|
|
214
|
+
### Mark Article as Read
|
|
215
|
+
|
|
216
|
+
Imagine you want to mark that an article has been read by the current user, after they've been on the page for a while and scrolled to the bottom. You could make a hook that looks something like this:
|
|
217
|
+
|
|
218
|
+
```tsx
|
|
219
|
+
import { useFetcher } from "react-router";
|
|
220
|
+
|
|
221
|
+
function useMarkAsRead({ articleId, userId }) {
|
|
222
|
+
const marker = useFetcher();
|
|
223
|
+
|
|
224
|
+
useSpentSomeTimeHereAndScrolledToTheBottom(() => {
|
|
225
|
+
marker.submit(
|
|
226
|
+
{ userId },
|
|
227
|
+
{
|
|
228
|
+
action: `/article/${articleId}/mark-as-read`,
|
|
229
|
+
method: "post",
|
|
230
|
+
},
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### User Avatar Details Popup
|
|
237
|
+
|
|
238
|
+
Anytime you show the user avatar, you could put a hover effect that fetches data from a loader and displays it in a popup.
|
|
239
|
+
|
|
240
|
+
```tsx filename=app/pages/user-details.tsx
|
|
241
|
+
import { useState, useEffect } from "react";
|
|
242
|
+
import { useFetcher } from "react-router";
|
|
243
|
+
import type { Route } from "./+types/user-details";
|
|
244
|
+
|
|
245
|
+
export async function loader({ params }: Route.LoaderArgs) {
|
|
246
|
+
return await fakeDb.user.find({
|
|
247
|
+
where: { id: params.id },
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
type LoaderData = Route.ComponentProps["loaderData"];
|
|
252
|
+
|
|
253
|
+
function UserAvatar({ partialUser }) {
|
|
254
|
+
const userDetails = useFetcher<LoaderData>();
|
|
255
|
+
const [showDetails, setShowDetails] = useState(false);
|
|
256
|
+
|
|
257
|
+
useEffect(() => {
|
|
258
|
+
if (
|
|
259
|
+
showDetails &&
|
|
260
|
+
userDetails.state === "idle" &&
|
|
261
|
+
!userDetails.data
|
|
262
|
+
) {
|
|
263
|
+
userDetails.load(`/user-details/${partialUser.id}`);
|
|
264
|
+
}
|
|
265
|
+
}, [showDetails, userDetails, partialUser.id]);
|
|
266
|
+
|
|
267
|
+
return (
|
|
268
|
+
<div
|
|
269
|
+
onMouseEnter={() => setShowDetails(true)}
|
|
270
|
+
onMouseLeave={() => setShowDetails(false)}
|
|
271
|
+
>
|
|
272
|
+
<img src={partialUser.profileImageUrl} />
|
|
273
|
+
{showDetails ? (
|
|
274
|
+
userDetails.state === "idle" && userDetails.data ? (
|
|
275
|
+
<UserPopup user={userDetails.data} />
|
|
276
|
+
) : (
|
|
277
|
+
<UserPopupLoading />
|
|
278
|
+
)
|
|
279
|
+
) : null}
|
|
280
|
+
</div>
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
## Conclusion
|
|
286
|
+
|
|
287
|
+
React Router offers a range of tools to cater to varied developmental needs. While some functionalities might seem to overlap, each tool has been crafted with specific scenarios in mind. By understanding the intricacies and ideal applications of `<Form>`, `useFetcher`, and `useNavigation`, along with how data flows through component props, developers can create more intuitive, responsive, and user-friendly web applications.
|
|
288
|
+
|
|
289
|
+
[form-component]: ../api/components/Form
|
|
290
|
+
[use-fetcher]: ../api/hooks/useFetcher
|
|
291
|
+
[use-navigation]: ../api/hooks/useNavigation
|
|
292
|
+
[network-concurrency-management]: ./concurrency
|