Skip to content

[all components] Do not use Math.random in useStableCallback - #4732

Merged
michaldudak merged 2 commits into
mui:masterfrom
michaldudak:useStableCallback-safe-react
May 5, 2026
Merged

michaldudak merged 2 commits into
mui:masterfrom
michaldudak:useStableCallback-safe-react

Conversation

@michaldudak

@michaldudak michaldudak commented May 4, 2026 •

Copy link
Copy Markdown
Member

Use SafeReact instead of nondeterministic code using Math.random to reference useInsertionEffect that is missing in older versions of React. This matches the usage for other features introduced after React 17.

Fixes #4729

@michaldudak michaldudak added the scope: all components Widespread work has an impact on almost all components. label May 4, 2026
@pkg-pr-new

pkg-pr-new Bot commented May 4, 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@4732
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@4732
    

commit: 1de7d60

@code-infra-dashboard

code-infra-dashboard Bot commented May 4, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react ▼-52B(-0.01%) ▼-39B(-0.03%)

Details of bundle changes

Performance

Total duration: 1,316.03 ms -32.84 ms(-2.4%) | Renders: 53 (+0) | Paint: 2,076.45 ms +0.72 ms(0.0%)

Test Duration Renders
Mixed surface mount (app-like density) 123.13 ms 🔺+25.08 ms(+25.6%) 5 (+0)
Select open (500 options) 65.81 ms 🔺+14.97 ms(+29.5%) 14 (+0)
Select mount (200 instances) 166.79 ms 🔺+11.80 ms(+7.6%) 3 (+0)
Scroll Area mount (300 instances) 64.06 ms ▼-27.94 ms(-30.4%) 3 (+0)
Slider mount (300 instances) 144.38 ms ▼-14.07 ms(-8.9%) 3 (+0)

…and 7 more — details


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

@netlify

netlify Bot commented May 4, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 1de7d60
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/69f8734dc585410008b65e10
😎 Deploy Preview https://deploy-preview-4732--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.

@michaldudak
michaldudak marked this pull request as ready for review May 4, 2026 10:25
@michaldudak
michaldudak requested a review from romgrk as a code owner May 4, 2026 10:25
@michaldudak michaldudak changed the title [all-components] Do not use Math.random in useStableCallback [all-components] Do not use Math.random in useStableCallback May 4, 2026
@michaldudak michaldudak changed the title [all-components] Do not use Math.random in useStableCallback [all components] Do not use Math.random in useStableCallback May 4, 2026

@LukasTy LukasTy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. 👍

Claude Opus 4.7 review

Surgical fix that replaces a Math.random()-at-module-scope minification workaround in useStableCallback.ts with a read from SafeReact, the existing namespace clone already used in this codebase for the same purpose (useId.ts, plus a handful of components for captureOwnerStack). Resolves a real production crash on Cloudflare Workers, where generating random values during module evaluation is disallowed and breaks any RSC/SSR chunk that imports a Base UI component depending on useStableCallback. Behavior is preserved across React 17, React 18+, and Preact. CI is fully green.

Context

  • Original workaround used (React as any)[\useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)]to defeat esbuild 0.19+ rewriting computed-string property access into direct named imports (mui/material-ui#41190). That static-string defeat works, but it pullsMath.random()` into the module's top-level evaluation.
  • Cloudflare Workers disallow random value generation in global scope, so the call throws Error: Disallowed operation called within global scope whenever Base UI is evaluated in a Worker (RSC client-reference chunks, SSR). See issue #4729 for the repro shape (React 19.2 + React Router 7 RSC + Vite RSC + Cloudflare).
  • SafeReact = { ...React } as typeof React defeats the same bundler optimization differently: reads go through a runtime-cloned object, which no minifier will inline back into a named React import. This is the same approach already in packages/utils/src/safeReact.ts and consumed by useId.ts:24 and several components.

Critical issues

None.

Suggestions

# File Line Suggestion Category
1 packages/utils/src/useStableCallback.ts 5 Optional: explicitly annotate the type to make the React 17 (undefined) case visible, mirroring useId.ts:24 (const maybeReactUseId: undefined | (() => string) = SafeReact.useId;). The trailing truthy check covers the runtime side either way, so this is purely a readability nit. Style

What looks good

  • Reuses existing infrastructure rather than introducing a new escape hatch. SafeReact is the established way Base UI reads APIs that may be missing on older React versions: useId.ts:24 (React 18 hook), and ~7 components reading captureOwnerStack (React 19 hook). Adding useInsertionEffect to the list is the same shape of change.
  • The expanded JSDoc on SafeReact is a real readability win. The previous file-level link to a year-old material-ui comment forced anyone curious to chase context off-repo. The new comment names the failure mode (bundlers rewriting direct property reads into named imports, which breaks React 17) right at the source.
  • Behavior preservation across all three target runtimes:
    • React 17: SafeReact.useInsertionEffect is undefined, truthy check fails, falls back to the no-op trampoline (fn) => fn(). Same as before.
    • Preact: spreading copies both useInsertionEffect and useLayoutEffect to the same function, so the useInsertionEffect !== SafeReact.useLayoutEffect identity check is false; falls back to the no-op trampoline. Same as before.
    • React 18+: SafeReact.useInsertionEffect is the real hook, distinct from useLayoutEffect; uses the real hook. Same as before.
  • Drops the now-unused import * as React from 'react' from useStableCallback.ts ‚Äî clean removal.
  • Slight bundle reduction (parsed -52B / gzip -39B per the code-infra-dashboard comment). The fix is essentially free.
  • All CI green: test-dev (macos/windows/ubuntu), JSDOM tests + React 18 variant, browser tests + React 18 + React Compiler variants, typechecking + React 18 variant, E2E, regression, linting, package verification, validating docs, argos visual tests.

Things worth verifying / non-blocking notes

  • The fix's robustness depends on bundlers being unable to track that SafeReact is structurally identical to React (which would let them re-inline SafeReact.useInsertionEffect into a named import). That tracking is well outside what esbuild and similar minifiers attempt, and the same pattern has lived in useId.ts without regression. No real risk, just naming the assumption.
  • There is no useStableCallback.test.ts (the neighboring useId.ts has useId.test.tsx). The change is structural and the React 17 / Preact branches are exercised indirectly by the wider component test suites (which CI runs against React 18 too), so the absence is not a blocker for this PR. Worth flagging if maintainers want a regression test for the fallback paths.
  • The Preact identity comparison (useInsertionEffect !== SafeReact.useLayoutEffect) reads useLayoutEffect from the same spread snapshot, so the comparison stays semantically equivalent to the previous React.useLayoutEffect read. Only matters if something mutates React.useLayoutEffect after safeReact.ts evaluates, which is not a realistic scenario.

Verdict

Approve. Tight, well-scoped fix that resolves a reproducible production bug, aligns with an existing pattern in the codebase, preserves behavior across all supported React/Preact runtimes, and improves readability of the workaround it leans on.

@michaldudak
michaldudak merged commit 8c5bdda into mui:master May 5, 2026
6 checks passed
@michaldudak
michaldudak deleted the useStableCallback-safe-react branch May 5, 2026 06:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: all components Widespread work has an impact on almost all components.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

@base-ui/utils/useStableCallback calls Math.random() at module scope

2 participants