React 的 useId 有什么用?为什么不能用 Math.random / Date 生成 id?

useId 生成跨服务端/客户端一致的唯一 ID,专为 SSR/SSG 设计。

为什么不能用 random/Date:

const id = useId()  // 如 ":r0:"
<label htmlFor={id} /><input id={id} />

在列表里需要多个 id 时,用 const base = useId(); const ids = items.map((_, i) => base + '-' + i)。

同分类其他题目