Hook useId giúp tạo ra các unique ID mà có thể dùng làm giá trị của các thuộc tính accessibility.
Context
Giả sử ta có một component như sau:
function PasswordField() {
return (
<>
<label htmlFor="password">Password: </label>
<input type="password" id="password" />
</>
)
}
export default PasswordFieldVà component App render component PasswordField hai lần:
import PasswordField from "./PasswordField"
function App() {
return (
<>
<h2>Choose password</h2>
<PasswordField />
<h2>Confirm password</h2>
<PasswordField />
</>
)
}
export default AppKhi đó, bởi vì cả hai thẻ <input> đều có cùng giá trị của id nên khi ta click vào label “Confirm password” thì nó lại focus vào input của “Choose password” (ô input đầu tiên). Việc gán cứng giá trị của id không phải là một cách làm tốt.
Usage
Thay vào đó, ta nên sử dụng unique ID:
import { useId } from "react"
function PasswordField() {
const id = useId()
return (
<>
<label htmlFor={id}>Password: </label>
<input type="password" id={id} />
</>
)
}
export default PasswordFieldNote
Không nên sử dụng hook này để tạo key cho các component, key nên được tạo từ dữ liệu.