LEARN REACT_MANAGING STATE_Preserving and Resetting State ๐Ÿ‘‰ ํ‚ค๊ฐ€ ํ•„์š”ํ•œ ์ด์œ 

์„œ์ •์ค€ยท2023๋…„ 7์›” 2์ผ
0

react.dev

๋ชฉ๋ก ๋ณด๊ธฐ
1/5

์ถœ์ฒ˜: React doc

Resetting state at the same position

  1. Render components in different positions
  2. Give each component an explicit identity with key

Option 1: Rendering a component in different positions

  • ์ฝ”๋“œ 1
 	  {isPlayerA ? (
        <Counter person="Taylor" />
      ) : (
        <Counter person="Sarah" />
      )}
  • ์ฝ”๋“œ 2
      {isPlayerA &&
        <Counter person="Taylor" />
      }
      {!isPlayerA &&
        <Counter person="Sarah" />
      }

๐Ÿ‘‰ ์ฝ”๋“œ 1์˜ ๊ฒฝ์šฐ ๊ฐ™์€ Counter๋กœ ์ธ์‹ํ•จ. ์ฝ”๋“œ 2์˜ ๊ฒฝ์šฐ ๋‹ค๋ฅธ Counter๋กœ ์ธ์‹ํ•˜์—ฌ state ๊ณต์œ ๋ฅผ ํ•˜์ง€ ์•Š์Œ.

This solution is convenient when you only have a few independent components rendered in the same place.

๐Ÿ‘‰ ๋‘๊ฐœ์˜ ๊ฐ™์€ component๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์œ ์šฉํ•œ ๋ฐฉ๋ฒ•.

Option 2: Resetting state with a key

{isPlayerA ? (
  <Counter key="Taylor" person="Taylor" />
) : (
  <Counter key="Sarah" person="Sarah" />
)}

You might have seen keys when rendering lists. Keys arenโ€™t just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent (โ€œfirst counterโ€, โ€œsecond counterโ€) to discern between components. But keys let you tell React that this is not just a first counter, or a second counter, but a specific counterโ€”for example, Taylorโ€™s counter. This way, React will know Taylorโ€™s counter wherever it appears in the tree!

This is why, even though you render them in the same place in JSX, React sees them as two different counters, and so they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed.

๐Ÿ‘‰ component์˜ ์ด๋ฆ„์ด ๊ฐ™์•„๋„ key๋ฅผ ๋ถ™์ด๋Š” ์ˆœ๊ฐ„ ๊ฐ๊ฐ ๋‹ค๋ฅธ component๋กœ ์ธ์‹ํ•œ๋‹ค. ๋‹ค๋ฅธ componet๋กœ ์ธ์‹๋˜๊ธฐ ๋•Œ๋ฌธ์— state๋ฅผ ์ ˆ๋Œ€๋กœ ๊ณต์œ ํ•˜์ง€ ์•Š๋Š”๋‹ค.

Note
Remember that keys are not globally unique. They only specify the position within the parent.

profile
ํ†ตํ†ตํ†ตํ†ต

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