Description
The randomID
fn returns a lightweight, pseudo-unique string by taking a random number, converting it to base-36,
and slicing out a portion. It prefixes the result with an underscore to avoid starting with a digit.
Warning: This approach is not cryptographically secure and may collide; for security-critical or
globally unique IDs, prefer crypto.randomUUID()
.
Code Byte
export const randomID = () => {
return '_' + Math.random().toString(36).substring(2, 9);
}
Use cases:
- DOM element IDs: Quickly assign unique id attributes during dynamic element creation.
- React keys: Provide temporary key props in lists when no stable identifier is available.
- Client-side caching: Tag cache entries or in-memory objects.
- Debug labels: Differentiate logs or objects during development.
Example usage:
import { randomID } from './random-id.util';
// Generating a unique key for localStorage entries
const sessionKey = `session_${randomID()}`;
localStorage.setItem(sessionKey, JSON.stringify({
step: 'onboarding',
startedAt: new Date().toISOString()
}));