Send Data Right Before a Page Closes in React
To send data to a server right before a page is closed or right before the user navigates to another page, call navigator.sendBeacon() when the visibilitychange event fires and document.visibilityState becomes hidden. Use this for analytics data that should be sent on exit, such as read progress (how far a reader got through an article) or time spent viewing the page.
In React, register the event in useEffect, and read the value to send from the latest state through useEffectEvent. In my test environment, I confirmed that the data reached the server when I navigated away with a link and when I closed the page. I also tested what happens with common mistakes and the limits of sendBeacon().
The test environment was Ubuntu 24.04, Node.js 22.23.4, React / react-dom 19.3.1, and TypeScript 7.0.2. I type-checked the code with tsc, bundled it with esbuild, and opened the development build wrapped in StrictMode in headless Chromium 153, driven by Playwright 1.63.0. The server that received the data was a Node.js server running inside the test environment. I could not reproduce tab switching or window minimizing in this environment, so I only tested two cases: navigating to another page with a link, and closing the page. I did not test Firefox, Safari, mobile browsers, real network transmission over the internet, or screen switches that do not reload the page, such as those done by React Router.

- 1. Use visibilitychange as the trigger for sending
- 2. A hook that sends when the page becomes hidden
- 3. An empty dependency array sends the first value
- 4. Without cleanup, the data is sent twice in development
- 5. The Content-Type depends on the form of the data
- 6. Sending a JSON Blob to a different origin may not arrive
- 7. Data over 64 KiB cannot be sent
- 8. When to use fetch with keepalive
Use visibilitychange as the trigger for sending
The MDN page for sendBeacon() says that if you want to send data when the user is done with the page, the most reliable approach is to send it in the visibilitychange event. The unload, beforeunload, and pagehide events may not fire at all, especially on smartphones. For example, this happens when the user switches to another app and then closes the browser from the app switcher.
According to the MDN page for the visibilitychange event, the change to hidden is the last event you can reliably detect on a page. It fires when navigating to another page, switching tabs, closing a tab, minimizing or closing the browser, or switching to another app on a smartphone.
In the Chromium test environment, I sent with sendBeacon() from each of the three events. All three arrived, in this order, both when I navigated to another URL and when I closed the page. At the time of pagehide, visibilityState was still visible.
1:beforeunload:visible / 2:pagehide:visible / 3:visibilitychange:hidden
A hook that sends when the page becomes hidden
The hook is as follows. When the page becomes hidden, it calls getBody() and sends the returned data to url.
import { useEffect, useEffectEvent } from 'react';
// When the page is hidden, send the result of getBody() to url
export function useSendOnHide(url: string, getBody: () => BodyInit | null) {
// Call getBody with the latest props and state at the time it is called
const onHide = useEffectEvent(() => {
const body = getBody();
if (body === null) return;
const queued = navigator.sendBeacon(url, body);
if (!queued) console.warn('sendBeacon が送信を受け付けませんでした');
});
useEffect(() => {
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden') onHide();
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => document.removeEventListener('visibilitychange', onVisibilityChange);
}, [url]);
}
The event is registered and removed in useEffect, and the function that builds the data to send is wrapped in useEffectEvent. According to the official useEffectEvent reference, a function created with useEffectEvent reads the latest props and state at the time it is called. It is also not included in the dependency array. So you can send the values as they were when the page became hidden, without re-registering the event every time the state changes. The official reference also includes an example of using useEffectEvent inside a custom hook (useInterval).
The caller only needs to pass a function that returns the data to send. In the following example, the article page sends how far the reader got (100% when scrolled to the bottom).
import { useEffect, useState } from 'react';
import { useSendOnHide } from './useSendOnHide';
// Read percentage (100 when scrolled to the bottom)
function useReadPercent() {
const [percent, setPercent] = useState(0);
useEffect(() => {
const onScroll = () => {
const max = document.documentElement.scrollHeight - window.innerHeight;
const now = Math.round((window.scrollY / max) * 100);
setPercent((p) => Math.max(p, now));
};
window.addEventListener('scroll', onScroll, { passive: true });
return () => window.removeEventListener('scroll', onScroll);
}, []);
return percent;
}
function ArticlePage() {
const percent = useReadPercent();
useSendOnHide('/log', () => JSON.stringify({ page: '/articles/1', percent }));
return (
<p>
読んだ割合:<output>{percent}</output>% <a href="/next">次のページへ</a>
</p>
);
}
The page used in the test also has body paragraphs for scrolling. In the test environment, I scrolled until the screen showed "48%", then navigated to another page with a link. The server received the following data. When I closed the page instead, the same data arrived.
{"page":"/articles/1","percent":48}
As noted on the MDN page for the visibilitychange event, visibilitychange also fires when switching tabs. This hook sends every time the page becomes hidden, so repeatedly switching away and back in one visit sends data multiple times. In this example, the "read percentage" only increases, so on the server side it is enough to use the largest value received from the same visit.
An empty dependency array sends the first value
If you read state directly inside an event handler in useEffect without useEffectEvent and use an empty dependency array, the stale value is sent.
function ArticlePage() {
const percent = useReadPercent();
useEffect(() => {
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon('/log', JSON.stringify({ page: '/articles/1', percent }));
}
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => document.removeEventListener('visibilitychange', onVisibilityChange);
}, []); // Mistake: percent is used, but the dependency array is empty
// ...
}
When I scrolled to 48% and then navigated in the same way, the server received 0%.
{"page":"/articles/1","percent":0}
The function registered with the event was created during the first render. The percent it captures stays at the 0 from that first render. The screen showed 48%, but 0% was sent.
Without cleanup, the data is sent twice in development
I also tested a version where useEffect does not return a function to remove the listener.
useEffect(() => {
// Mistake: does not return a function that calls removeEventListener
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') onHide();
});
}, []);
The number of requests received when navigating with a link was as follows.
| Approach | With StrictMode | Without StrictMode |
|---|---|---|
| No cleanup | 2 | 1 |
| The hook in this article | 1 | 1 |
As described in the official StrictMode reference, in development StrictMode runs each Effect's setup and cleanup one extra time. Without a cleanup function, two listeners stayed registered, and the data was sent twice. The official reference describes this behavior as a way to find missing cleanup.
The Content-Type depends on the form of the data
sendBeacon() accepts strings as well as Blob, URLSearchParams, FormData, and others (MDN page for sendBeacon()). In the test environment, the Content-Type received by a server on the same origin was as follows. All of these were sent with POST.
| Value passed | Content-Type received by the server |
|---|---|
String from JSON.stringify() |
text/plain;charset=UTF-8 |
Blob with type: 'application/json' |
application/json |
URLSearchParams |
application/x-www-form-urlencoded;charset=UTF-8 |
FormData |
multipart/form-data; boundary=… |
If you pass a JSON string as is, the Content-Type becomes text/plain. If your server reads the body as JSON based on the Content-Type, wrap it in a Blob and specify application/json. However, if the destination is a different origin, the problem described in the next section occurs.
Sending a JSON Blob to a different origin may not arrive
The analytics server may be on a different origin from the page. In the test environment, I sent to a different origin (localhost:3001) that did not return CORS headers, and the results were as follows.
戻り値 [["文字列",true],["Blob(application/json)",true]]
3001 POST /log/string | text/plain;charset=UTF-8 | origin http://localhost:3000 | {"percent":48}
3001 OPTIONS /log/blob | null | origin http://localhost:3000 |
The string arrived as a POST as-is. For the application/json
Blob, only the OPTIONS request (the preflight) arrived first, and the POST carrying the data never arrived.
The Beacon specification says that when the Content-Type is not a value that can be sent without a CORS check (such as text/plain), the request is sent in CORS mode. According to the privacy and security section of the specification, a preflight is performed in this case, and the destination server must return permission through headers such as Access-Control-Allow-Origin.
In this case, sendBeacon() returned true. true means the send was accepted for queuing, not that it arrived. If you send application/json to a different origin, confirm that the destination server returns CORS permission.
Data over 64 KiB cannot be sent
According to MDN, the total size of data queued for sending with sendBeacon() is limited to 64 KiB (65,536 bytes), and false is returned when the request is not accepted. The results in the test environment were as follows.
{"65536 バイト":true,"65537 バイト":false}
40000 バイトを続けて2回 [true,false]
fetch keepalive で 65537 バイト TypeError: Failed to fetch
65,536 bytes was accepted, and one byte more returned false. When I sent 40,000 bytes twice in a row, the second call returned false. The Fetch specification decides whether the 64 KiB limit is exceeded by counting together the keepalive requests that have not finished sending. The Beacon specification says that sendBeacon() shares the same limit as keepalive in fetch(). So even if you resend with fetch() and keepalive after false is returned, the limit does not increase. In the test environment, fetch() with keepalive also failed when I tried to send 65,537 bytes in one request.
The hook logs a warning to the console when false is returned.
Use sendBeacon() only for small data that fits within 64 KiB. If other requests are sent at the same time, their sizes count toward the total.
When to use fetch with keepalive
According to the MDN explanation of fetch() options, a fetch() with keepalive: true is not aborted by the browser when the page is closed. Use it instead of sendBeacon() when you need a method other than POST, when you want to set headers in detail, or when you want to receive the server's response.
fetch('/log', { method: 'POST', body, keepalive: true });
In the test environment, both fetch() with keepalive and fetch() without it reached the server, both when navigating and when closing the page. Adding a 1-second network delay with the Chrome DevTools Protocol gave the same results. However, MDN explains that a request keeps being sent after the page is closed only when keepalive is set. The fact that a fetch() without keepalive arrived is a result from this test environment only.





