Skip to content

[docs] Clean up timeout handling in useEffect in GoogleAnalyticsProvider - #5760

Merged
michaldudak merged 7 commits into
mui:masterfrom
sai6855:effect-clean-up-ga
Sep 21, 2026
Merged

michaldudak merged 7 commits into
mui:masterfrom
sai6855:effect-clean-up-ga

Conversation

@sai6855

@sai6855 sai6855 commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

I ran npx react-doctor@latest from React Doctor in the docs folder. It scans the codebase for inefficient React patterns and potential improvements.

It identified a bunch of issues, and I’ll be creating separate PRs to address them. This is the first PR in that series.

React Doctor identified timer without cleanup in docs/src/blocks/GoogleAnalyticsProvider.tsx, This PR addresses that issue

@sai6855 sai6855 added docs Improvements or additions to the documentation. type: enhancement It’s an improvement, but we can’t make up our mind whether it's a bug fix or a new feature. labels Sep 19, 2026
@sai6855

sai6855 commented Sep 19, 2026

Copy link
Copy Markdown
Member Author

@claude review

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

PR review

The change is behavior-preserving for the real flows: the old clearTimeout at the top of the effect and the new cleanup both collapse the Strict Mode double-invoke and the route-change re-run to a single page_view, and GoogleAnalyticsProvider is mounted once at the app root (docs/src/components/GoogleAnalytics.tsx:19) so it never remounts per route. Nothing is merge-blocking. The one thing worth fixing is that the refactor leaves behind a ref the effect no longer needs, where the repo's useTimeout utility would do the whole job.

Bugs (1)

1. ℹ️ Pending page_view is now cancelled on unmount instead of firing

Location: docs/src/blocks/GoogleAnalyticsProvider.tsx:86

return () => {
  clearTimeout(timeout.current ?? undefined);
};

Previously the only clearTimeout ran at the start of the next effect run, so a timeout still pending when the provider unmounted would fire and send the event. Now it is cancelled. This is the correct React behavior (and what the PR intends), and it is not realistically reachable here — the timeout has no delay, so it resolves on the next macrotask, and the provider lives at the app root — but it is the one observable delta versus the base version, so flagging it for the record rather than as a defect.

Failure scenario: An app-root unmount within the same tick as a route change would drop one page_view beacon that the old code would have sent. Not reachable in the docs app as structured.

Fix: None required; noting the intentional behavior change.

Simplifications (1)

1. 🟠 timeout ref is now redundant — use useTimeout (or a local variable)

Location: docs/src/blocks/GoogleAnalyticsProvider.tsx:68

const timeout = React.useRef<ReturnType<typeof setTimeout> | null>(null);

React.useEffect(() => {
  timeout.current = setTimeout(() => { /* ... */ });

  return () => {
    clearTimeout(timeout.current ?? undefined);
  };
}, [currentRoute, productCategoryId, productId]);

The ref existed only so the next effect run could reach the previous timer id. Once the id is cleared from the same effect's cleanup, the closure already has it, so the ref, its ReturnType<typeof setTimeout> | null annotation, and the ?? undefined coercion are all dead weight — timeout has no other reader in the file. It also leaves a stale id in timeout.current after clear/fire, which is harmless today but is exactly the kind of shared mutable slot a later edit trips over.

The repo guideline is stronger than that: "Always use the useTimeout utility from @base-ui/utils/useTimeout instead of window.setTimeout." The docs app already follows it in Demo.tsx:40, SearchDialog.tsx:47, useSearchTracking.ts:22, SearchControls.tsx:49, and others. Timeout.start() clears any previously scheduled call and useTimeout() disposes on unmount, so it reproduces both halves of this PR's intent with no ref and no manual cleanup.

Failure scenario: A file whose entire stated purpose is "clean up timeout handling" keeps a hand-rolled ref plus null-coercion that the surrounding codebase has a shared utility for, so the next reader has to re-derive why the ref is there (it isn't needed) and the convention stays inconsistent across docs/src.

Fix:

import { useTimeout } from '@base-ui/utils/useTimeout';

const pageViewTimeout = useTimeout();

React.useEffect(() => {
  // Wait for the title to be updated.
  pageViewTimeout.start(0, () => {
    // Remove hash as it's never sent to the server
    // https://github.com/vercel/next.js/issues/25202
    const canonicalAsServer = window.location.pathname.replace(/#(.*)$/, '');

    // https://developers.google.com/analytics/devguides/collection/ga4/views?client_type=gtag
    window.gtag('event', 'page_view', {
      page_title: document.title,
      page_location: canonicalAsServer,
      productId,
      productCategoryId,
    });
  });
}, [pageViewTimeout, currentRoute, productCategoryId, productId]);

Note that useTimeout clears only on unmount, not on dep change — start() clearing the prior call covers the re-run case, which matches the base behavior. If you prefer to stay with plain setTimeout, the minimal version still drops the ref:

React.useEffect(() => {
  const timeoutId = setTimeout(() => { /* ... */ });
  return () => clearTimeout(timeoutId);
}, [currentRoute, productCategoryId, productId]);

Verdict

Approve after nits — the timeout lifecycle is correct and behavior-preserving; the only outstanding item is dropping the now-unused ref in favor of the repo's useTimeout utility.


🤖 Review generated with Claude Code · Opus 5 (High) · medium review depth · 16 turns · 1m30s · $0.60 · run

@pkg-pr-new

pkg-pr-new Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@5760
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@5760
    

commit: 5419b07

@code-infra-dashboard

code-infra-dashboard Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 0B(0.00%) 0B(0.00%)

Details of bundle changes

Performance

Total duration: 930.42 ms +25.65 ms(+2.8%) | Renders: 76 (+0) | Paint: 1,562.16 ms +41.76 ms(+2.7%)

Test Duration Renders
Dialog mount (300 instances) 27.79 ms 🔺+4.89 ms(+21.3%) 1 (+0)

14 tests within noise — details


Check out the code infra dashboard for more information about this PR.

@netlify

netlify Bot commented Sep 19, 2026

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit d1593bc
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6aae1c4240208d0008c01a37
😎 Deploy Preview https://deploy-preview-5760--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 5419b07
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6aae28bf68a2940008b57cb5
😎 Deploy Preview https://deploy-preview-5760--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The raw timer should use the repository’s shared useTimeout utility.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
What changed in this PR

Simplifies delayed Google Analytics page-view tracking cleanup.

Changes:

  • Replaces the persistent timeout ref with effect-local cleanup.
File Description
docs/​src/​blocks/​GoogleAnalyticsProvider.tsx Cleans up the page-view timeout when the effect reruns or unmounts.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

userLanguage,
children,
}: GoogleAnalyticsProviderProps) {
const timeout = useTimeout();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Used repo level utility instead of raw setTimeOut

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The new React.useCallback conflicts with the repository’s callback convention.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
Resolved since last review (1)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The extra dependency argument passed to useStableCallback causes a TypeScript error.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 High severity

Open (1)
Resolved since last review (1)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The focused change correctly prevents pending timer callbacks after effect cleanup and follows repository conventions.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@sai6855
sai6855 marked this pull request as ready for review September 19, 2026 06:23
@sai6855
sai6855 requested a review from atomiks as a code owner September 19, 2026 06:23
@michaldudak
michaldudak merged commit 95780fa into mui:master Sep 21, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to the documentation. type: enhancement It’s an improvement, but we can’t make up our mind whether it's a bug fix or a new feature.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants