[React 18] useId
A new hook for version 18 of React is useId
. Frequently in React you need unique identifiers to associate two objects together. An example of this would be making sure a label and an input are associated together by the htmlFor
attribute.
Previously you could maintain some sort of unique counter that was tracked across renders. With concurrent React and batching in version 18 that's no longer possible. useId
will give you a consistent via a hook so that they can always be the same.
This is useful for the thing we see above: we have a label which needs a for
attribute that corresponds to an input. We would either need to use some piece of data/parameter that we'd pass into the component that would serve as the key or we can use this hook to give it a unique ID.
If you need multiple IDs in the same component just do {id}-name
, {id}-address
, ``{id}-number, etc. No need to call
useId` multiple times.
This is safe across server-side renders and client-side.
import { useId } from 'react';
function LabelInputPair() {
const id = useId();
return (
<div style={{ marginBottom: '50px' }}>
<label htmlFor={id}>
Click on this label and it'll highlight the input {id}
</label>
<br />
<input type="text" id={id} placeholder={`input id ${id}`} />
</div>
);
}
export default function UseIdComponent() {
return (
<>
<LabelInputPair />
<LabelInputPair />
<LabelInputPair />
<LabelInputPair />
</>
);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-12-09 [Web] Possible bug for Cache the network request
2020-12-09 [Javascript] Broadcaster + Operator + Listener pattern -- 25. Save Network Requests by Using a Cache
2020-12-09 [Java Spring] Aspect
2019-12-09 [Algorithm] 242. Valid Anagram
2019-12-09 [Algorithm] 155. Min Stack
2017-12-09 [Python] Format Strings in Python
2017-12-09 [Python] Execute a Python Script