UNPKG

7.6 kB Markdown View Raw
1---
2title: Network Concurrency Management
3---
4
5# Network Concurrency Management
6
7[MODES: framework, data]
8
9<br/>
10<br/>
11
12When 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
14To 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
18React 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
34While 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
36React 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
38For 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
40Using this key:
41
42- `|`: Submission begins
43- ✓: Action complete, data revalidation begins
44- ✅: Revalidated data is committed to the UI
45- ❌: Request cancelled
46
47We can visualize this scenario in the following diagram:
48
49```text
50submission 1: |----✓-----✅
51submission 2: |-----✓-----✅
52submission 3: |-----✓-----✅
53```
54
55However, 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
58submission 1: |----✓---------❌
59submission 2: |-----✓-----✅
60submission 3: |-----✓-----✅
61```
62
63Because 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
67It'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
79The 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
83In 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
86export async function loader({ request }) {
87 const { searchParams } = new URL(request.url);
88 const cities = await searchCities(searchParams.get("q"));
89 return cities;
90}
91
92export 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
129All 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
133React 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
136
\No newline at end of file