diff --git a/packages/gitbook/src/components/Insights/InsightsProvider.tsx b/packages/gitbook/src/components/Insights/InsightsProvider.tsx index e28262dc0..b2b7f219c 100644 --- a/packages/gitbook/src/components/Insights/InsightsProvider.tsx +++ b/packages/gitbook/src/components/Insights/InsightsProvider.tsx @@ -86,15 +86,6 @@ export function InsightsProvider(props: InsightsProviderProps) { | undefined; }>({}); - /** - * Get the visitor ID and store it in a ref. - */ - React.useEffect(() => { - getVisitorId().then((visitorId) => { - visitorIdRef.current = visitorId; - }); - }, []); - /** * Synchronously flush all the pending events. */ @@ -194,13 +185,19 @@ export function InsightsProvider(props: InsightsProviderProps) { }, ); - // When the page is unloaded, flush all events + /** + * Get the visitor ID and store it in a ref. + */ React.useEffect(() => { - window.addEventListener('beforeunload', flushEventsSync); + getVisitorId().then((visitorId) => { + visitorIdRef.current = visitorId; + // When the page is unloaded, flush all events, but only if the visitor ID is set + window.addEventListener('beforeunload', flushEventsSync); + }); return () => { window.removeEventListener('beforeunload', flushEventsSync); }; - }, [flushEventsSync]); + }, []); return (