Repository navigation
[all components] Do not use Math.random in useStableCallback - #4732
Conversation
commit: |
Bundle size
PerformanceTotal duration: 1,316.03 ms -32.84 ms(-2.4%) | Renders: 53 (+0) | Paint: 2,076.45 ms +0.72 ms(0.0%)
…and 7 more — details Check out the code infra dashboard for more information about this PR. |
✅ Deploy Preview for base-ui ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify project configuration. |
Math.random in useStableCallback
Math.random in useStableCallbackMath.random in useStableCallback
LukasTy
left a comment
There was a problem hiding this comment.
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 scopewhenever 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 Reactdefeats 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 inpackages/utils/src/safeReact.tsand consumed byuseId.ts:24and 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.
SafeReactis the established way Base UI reads APIs that may be missing on older React versions:useId.ts:24(React 18 hook), and ~7 components readingcaptureOwnerStack(React 19 hook). AddinguseInsertionEffectto the list is the same shape of change. - The expanded JSDoc on
SafeReactis a real readability win. The previous file-level link to a year-oldmaterial-uicomment 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.useInsertionEffectisundefined, truthy check fails, falls back to the no-op trampoline(fn) => fn(). Same as before. - Preact: spreading copies both
useInsertionEffectanduseLayoutEffectto the same function, so theuseInsertionEffect !== SafeReact.useLayoutEffectidentity check is false; falls back to the no-op trampoline. Same as before. - React 18+:
SafeReact.useInsertionEffectis the real hook, distinct fromuseLayoutEffect; uses the real hook. Same as before.
- React 17:
- Drops the now-unused
import * as React from 'react'fromuseStableCallback.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
SafeReactis structurally identical toReact(which would let them re-inlineSafeReact.useInsertionEffectinto a named import). That tracking is well outside what esbuild and similar minifiers attempt, and the same pattern has lived inuseId.tswithout regression. No real risk, just naming the assumption. - There is no
useStableCallback.test.ts(the neighboringuseId.tshasuseId.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) readsuseLayoutEffectfrom the same spread snapshot, so the comparison stays semantically equivalent to the previousReact.useLayoutEffectread. Only matters if something mutatesReact.useLayoutEffectaftersafeReact.tsevaluates, 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.
Use
SafeReactinstead of nondeterministic code usingMath.randomto referenceuseInsertionEffectthat is missing in older versions of React. This matches the usage for other features introduced after React 17.Fixes #4729