useId는 React 18에서 추가된 Hook으로 고유 ID를 생성하는 Hook이다.
useId()
없음
고유 ID 문자열을 반환한다.
<label>
Password:
<input
type="password"
aria-describedby="password-hint"
/>
</label>
<p id="password-hint">
The password should contain at least 18 characters
</p>
React에서 ID를 직접 코드에 입력하는 것은 좋은 사례가 아니다. 페이지에서 컴포넌트는 몇 번이고 렌더링 될 수 있지만 ID는 고유해야 한다. useID를 활용하면 ID를 코드에 직접 입력하는 대신 고유한 ID를 생성할 수 있다.
이렇게 하면 이 컴포넌트를 재사용해도 생성된 ID는 충돌하지 않는다.
import { useId } from 'react';
export default function Form() {
const id = useId();
return (
<form>
<label htmlFor={id + '-firstName'}>First Name:</label>
<input id={id + '-firstName'} type="text" />
<hr />
<label htmlFor={id + '-lastName'}>Last Name:</label>
<input id={id + '-lastName'} type="text" />
</form>
);
}
여러 관련 요소에 ID를 제공해야 하는 경우, useId를 호출하여 공유 접두사를 생성할 수 있다.
/* Index.js */
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const root1 = createRoot(document.getElementById('root1'), {
identifierPrefix: 'my-first-app-'
});
root1.render(<App />);
const root2 = createRoot(document.getElementById('root2'), {
identifierPrefix: 'my-second-app-'
});
root2.render(<App />);
/* App.js */
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
console.log('Generated identifier:', passwordHintId)
return (
<>
<label>
Password:
<input
type="password"
aria-describedby={passwordHintId}
/>
</label>
<p id={passwordHintId}>
The password should contain at least 18 characters
</p>
</>
);
}
export default function App() {
return (
<>
<h2>Choose password</h2>
<PasswordField />
</>
);
}
하나의 페이지에서 여러 개의 독립된 React 애플리케이션을 렌더링하는 경우, useId로 생성된 모든 식별자가 별개의 접두사로 시작하므로 서로 다른 두 개의 앱에서 생성된 ID가 충돌하지 않는 것을 보장한다.
useId를 리스트의 key를 생성하기 위해 사용하면 안된다.
import { useId } from 'react';
import './App.css'
function App() {
const people = ["Stroud", "Collins", "Dell", "Anderson", "Hunter"];
const key = useId() // 이렇게 하면 안됨!
return (
<div>
{people.map((person) => (
<div key={key}> // 이렇게 하면 안됨!
{person}
</div>
))}
</div>
);
}
export default App;

키가 중복되었으며 이 동작은 지원되지 않고 추후에 변경될 수 있다는 경고문이 콘솔에 출력된다.
key는 반드시 데이터에서 생성되어야 한다!