Skip to content

Commit

Permalink
[useId] Trade random collisions for collisions on overflow (#29781)
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon authored Nov 25, 2021
1 parent 0dd15dd commit febe13a
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/mui-utils/src/useId.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import * as React from 'react';

let globalId = 0;

This comment has been minimized.

Copy link
@make-github-pseudonymous-again

make-github-pseudonymous-again Jan 21, 2022

Although 9007199254740992 is a pretty large number, if you want to avoid collisions on overflow (and in JavaScript it's pretty bad, try Math.pow(2,53) + 1, use globalId = 0n and ++globalId. You could also try globalId = 0 and globalId = globalId + 1 | 0 but that would overflow after Math.pow(2,31) - 1 and send you to negative numbers.

export default function useId(idOverride?: string): string | undefined {
const [defaultId, setDefaultId] = React.useState(idOverride);
const id = idOverride || defaultId;
React.useEffect(() => {
if (defaultId == null) {
// Fallback to this default id when possible.
// Use the random value for client-side rendering only.
// Use the incrementing value for client-side rendering only.
// We can't use it server-side.
setDefaultId(`mui-${Math.round(Math.random() * 1e9)}`);
// If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem
globalId += 1;
setDefaultId(`mui-${globalId}`);
}
}, [defaultId]);
return id;
Expand Down

0 comments on commit febe13a

Please sign in to comment.