๋ฐ˜์‘ํ˜•

useId ์†Œ๊ฐœ


useId()๋Š” React 18 ๋ฒ„์ „์— ๋„์ž…๋œ ํ›…์œผ๋กœ, ๋…ธ๋“œ์˜ ํŠธ๋ฆฌ ์œ„์น˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ณ ์œ  ID(Base32 ๋ฌธ์ž์—ด)๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์ปดํฌ๋„ŒํŠธ ํŠธ๋ฆฌ๊ฐ€ ์—ฌ๋Ÿฌ ์ž์‹(children)์œผ๋กœ ๋ถ„๊ธฐ๋  ๋•Œ๋งˆ๋‹ค ID์— ์ถ”๊ฐ€ ๋น„ํŠธ๋ฅผ ์‚ฝ์ž…ํ•ด์„œ ๊ฐ ์ž์‹์˜ ์œ„์น˜๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.

:r0: (๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ)
:r1: (์ž์‹ ์ปดํฌ๋„ŒํŠธ1)
:r2: (์ž์‹ ์ปดํฌ๋„ˆํŠธ2)
...

 

์ฃผ๋กœ ์„œ๋ฒ„ / ํด๋ผ์ด์–ธํŠธ์—์„œ ์ƒ์„ฑํ•œ ํŠธ๋ฆฌ(tree) ์‚ฌ์ด์˜ ํ•˜์ด๋“œ๋ ˆ์ด์…˜(hydration) ๋ถˆ์ผ์น˜(mismatch)๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค. ์ฆ‰, useId๊ฐ€ ์ƒ์„ฑํ•œ ๊ณ ์œ ํ•œ ID๋ฅผ ์ด์šฉํ•ด ์›ํ™œํ•œ ํ•˜์ด๋“œ๋ ˆ์ด์…˜์„ ๋•๋Š” ๋ชฉ์ ์ธ ๊ฒƒ. ๋ฆฌ์ŠคํŠธ์˜ key๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•œ ๋ชฉ์ ์ด ์•„๋‹ˆ๋ฏ€๋กœ ์ฃผ์˜ํ•œ๋‹ค.

 

์ถœ๋ ฅ๊ฐ’ ์˜ˆ์‹œ


๐Ÿ’ก : (์ฝœ๋ก )์€ querySelector ๊ฐ™์€ CSS ์…€๋ ‰ํ„ฐ์—์„  ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค(\ ๋ฐฑ์Šฌ๋ž˜์‹œ๋กœ ์ด์Šค์ผ€์ดํ”„ํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์žˆ๋‹ค). useId๋Š” : ํ† ํฐ์„ ํฌํ•จํ•œ ๋ฌธ์ž์—ด์„ ์ƒ์„ฑํ•˜๋ฏ€๋กœ CSS ์…€๋ ‰ํ„ฐ์—์„  ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

// App.js
function App() {
  const id = useId();
  return (
    <div>
      <h3>{`App - ${id}`}</h3> {/* App - :r0: */}
      <Child /> {/* Child - :r1: SubChild - :r2: */}
      <Child /> {/* Child - :r3: SubChild - :r4: */}
    </div>
  );
} 

// Child.js
function Child() {
  const id = useId();
  return (
    <div>
      <h3>{`Child - ${id}`}</h3>
      <SubChild />
    </div>
  );
} 

// SubChild.js
export default function SubChild() {
  const id = useId();
  return <h3>{`SubChild - ${id}`}</h3>;
}

 

ํ™”๋ฉด ์ถœ๋ ฅ ๊ฒฐ๊ณผ โ–ผ

App - :r0:
Child - :r1:
SubChild - :r2:
Child - :r3:
SubChild - :r4:

 

์ฐธ๊ณ ๋กœ ๋™์ผ ์ปดํฌ๋„ŒํŠธ์—์„œ useId ํ›…์„ ์—ฌ๋Ÿฌ๋ฒˆ ํ˜ธ์ถœํ•˜๋ฉด ๊ฐ๊ฐ ๋‹ค๋ฅธ ID๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

// App.js
const id1 = useId();
const id2 = useId();
console.log(id1, id2); // :r0: :r1:

 

ํ™œ์šฉ ์˜ˆ์‹œ


<label> โ‡„ <input> ์š”์†Œ๋ฅผ ์—ฐ๊ฒฐํ•  ๋•Œ useIdํ›…์ด ์ƒ์„ฑํ•œ ์œ ๋‹ˆํฌ ID๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. 

// Basic Example via React ๊ณต์‹ ๋ฌธ์„œ
function Checkbox() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Do you like React?</label>
      <input id={id} type="checkbox" name="react" />
    </>
  );
}

 

์—ฌ๋Ÿฌ ํ•„๋“œ์— ์‚ฌ์šฉํ•  ๋• ์œ ๋‹ˆํฌ ID + ์ ‘๋ฏธ์‚ฌ ๋ฐฉ์‹์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

// Multiple Fields Example via React ๊ณต์‹ ๋ฌธ์„œ
function NameFields() {
  const id = useId();
  return (
    <div>
      <label htmlFor={id + '-firstName'}>First Name</label>
      <div>
        <input id={id + '-firstName'} type="text" />
      </div>
      <label htmlFor={id + '-lastName'}>Last Name</label>
      <div>
        <input id={id + '-lastName'} type="text" />
      </div>
    </div>
  );
}

 

์ฐธ๊ณ ๊ธ€


 


๊ธ€ ์ˆ˜์ •์‚ฌํ•ญ์€ ๋…ธ์…˜ ํŽ˜์ด์ง€์— ๊ฐ€์žฅ ๋น ๋ฅด๊ฒŒ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค. ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”
๋ฐ˜์‘ํ˜•