๐Ÿ”‘ key

๊น€์ฒ ์ค€ยท2022๋…„ 1์›” 18์ผ
0

REACT

๋ชฉ๋ก ๋ณด๊ธฐ
9/38
post-custom-banner

๐Ÿ”‘ key

ํ‚ค๋Š” DOM ์š”์†Œ๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” ์œ ์ผํ•œ ๊ฒƒ์ด๋‹ค.

  • Virtual DOM์„ ๋น„๊ตํ•˜๋Š” ๊ณผ์ •์—์„œ key๊ฐ€ ์žˆ๋‹ค๋ฉด ๋”์šฑ ๋น ๋ฅด๊ฒŒ ์•Œ์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

  • ํ‚ค๊ฐ€ ์ด์ „๊ณผ ๊ฐ™์œผ๋ฉด React๋Š” DOM ์š”์†Œ๊ฐ€ ์ด์ „๊ณผ ๋™์ผํ•œ ๊ตฌ์„ฑ ์š”์†Œ๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค.

  • key ๊ฐ’์€ ์ค‘์ฒฉ๋˜๋ฉด ์•ˆ๋œ๋‹ค. key ๊ฐ’์€ ์–ธ์ œ๋‚˜ ์œ ์ผํ•ด์•ผํ•œ๋‹ค.

  • ๋ฆฌ์ŠคํŠธ ํ•ญ๋ชฉ์— ๋ช…์‹œ์ ์œผ๋กœ key๋ฅผ ์ง€์ •ํ•˜์ง€ ์•Š์œผ๋ฉด React๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ธ๋ฑ์Šค๋ฅผ key๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

  • key์— ์ธ๋ฑ์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ๊ถŒ์žฅํ•˜์ง€ ์•Š๋Š”๋‹ค.

๐Ÿค” key์— index๊ฐ’์„ ์“ฐ๋Š” ๊ฒƒ์„ ๊ถŒ์žฅํ•˜์ง€ ์•Š์„๊นŒ?

๋ฐ˜๋ณต๋˜๋Š” ๋ฆฌ์ŠคํŠธ๋‚˜ ์•„์ดํ…œ์˜ key๋กœ index๋ฅผ ์‚ฌ์šฉํ•˜์˜€์„ ๋•Œ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜๋ณตํ•˜๋Š”๋ฐ ์“ฐ์ด๋Š” ๋ฐฐ์—ด์—์„œ ์š”์†Œ๊ฐ€ ์ƒ์„ฑ,์ œ๊ฑฐ,๋ณ€๊ฒฝ๋˜์—ˆ์„ ๊ฒฝ์šฐ key๊ฐ€ ์ด๋ฅผ ์ถ”์ ํ•˜๊ธฐ ์–ด๋ ต๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.


๐Ÿ“ list and key

import React from "react";

const Test = () => {
  const fruits = ["apple", "banana", "carrot"];
  return (
    <div>
      {fruits.map((fruit,index) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </div>
  );
};

export default Test;
  • ๋ฐ˜๋ณต๋˜๋Š” ์—ฌ๋Ÿฌ๊ฐœ์˜ ์š”์†Œ๋ฅผ ๋‚˜์—ดํ•  ๋•Œ key๊ฐ’์„ ์ž…๋ ฅํ•ด์ค€๋‹ค.
    ์ด์œ ๋Š” key๋Š” ์š”์†Œ์˜ ๋ณ€ํ™” ์ถ”์ ์„ ๋” ๋นจ๋ฆฌ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ฃผ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

  • ์ด ๋•Œ ์œ„์—์„œ ์–ธ๊ธ‰ํ–ˆ๋“ฏ์ด ๋˜๋„๋ก์ด๋ฉด index(map์˜ ๋‘๋ฒˆ์งธ ํŒŒ๋ฆฌ๋ฏธํ„ฐ)๋ฅผ ํ‚ค ๊ฐ’์œผ๋กœ ํ• ๋‹นํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

๊ทธ๋ ‡๋‹คํ•ด๋„ index๋ฅผ key ๊ฐ’์œผ๋กœ ์จ๋„ ๊ดœ์ฐฎ์€ ๊ฒฝ์šฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
1. ๋ฐฐ์—ด๊ณผ ์š”์†Œ๋“ค์ด ๊ณ„์‚ฐ๋˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝ๋˜์ง€ ์•Š์„ ๋•Œ
2. ๋ฐฐ์—ด์ด ์žฌ์ •๋ ฌ์ด๋‚˜ ํ•„ํ„ฐ๋ง์ด ๋˜์ง€ ์•Š์„ ๋•Œ

์ฐธ์กฐ : Index as a key is an anti-pattern
Reconciliation

post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€