crypto.randomUUID() — สร้าง UUID v4 ใน browser และ Node.js โดยไม่ต้องลง library
Web Crypto API มี randomUUID() ในตัว — ไม่ต้อง import uuid หรือ nanoid เพื่อแค่สร้าง unique ID
// ก่อน — ต้อง install package
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4(); // 'a1b2c3d4-...'
// ตอนนี้ — built-in ใน browser และ Node.js 14.17+
const id = crypto.randomUUID(); // 'a1b2c3d4-e5f6-4a7b-8c9d-e0f1a2b3c4d5'
รองรับทั้ง browser (secure context เท่านั้น) และ Node.js:
// ใช้ใน loop ก็ได้
const ids = Array.from({ length: 5 }, () => crypto.randomUUID());
// ใช้เป็น key ใน React
items.map((item) => ({ ...item, id: crypto.randomUUID() }));
ถ้าต้องการ random bytes ธรรมดา ใช้ crypto.getRandomValues():
const array = new Uint8Array(16);
crypto.getRandomValues(array); // fill ด้วย random bytes
⚠️ Math.random() ไม่ cryptographically secure — ใช้ crypto แทนเสมอเมื่อต้องการ uniqueness ที่น่าเชื่อถือ