Skip to content

State, Rerendering, Shallow Compare

๊น€์„œ์ง„ edited this page Nov 29, 2021 · 2 revisions

https://github.com/boostcampwm-2021/web09-Duxcord/commit/c0ed2fb9214db122e93d09a033c6ae2a234f1170 client/src/components/Chat/index.tsx์˜ 61-62์ค„

1. Shallow Compare

object, array์˜ ๊ฐ™๊ณ  ๋‹ค๋ฆ„์„ ๋น„๊ตํ•  ๋•Œ attribute๋ฅผ ๋น„๊ตํ•˜์ง€ ์•Š๊ณ  reference๋งŒ ๋น„๊ตํ•˜๋Š” ๋ฐฉ์‹

๊ฐ™์€ ๊ฐ’์ด ๋“ค์–ด์žˆ๋Š” object๋„ reference๊ฐ€ ๋‹ค๋ฅด๋ฉด ๋‹ค๋ฅด๊ฒŒ ์ธ์‹ํ•˜๋ฉฐ,

๋‹ค๋ฅธ ๊ฐ’์ด ๋“ค์–ด์žˆ๋Š” object๋„ reference๊ฐ€ ๊ฐ™์œผ๋ฉด ๊ฐ™๊ฒŒ ์ธ์‹ํ•œ๋‹ค.

2. Re - Rendering

๋ฆฌ๋ Œ๋”๋ง์ด ๋ฐœ์ƒํ•˜๋Š” ์‹œ์  ๋‹ค์„ฏ ๊ฐ€์ง€!

  1. state ๋ณ€๊ฒฝ์ด ์žˆ์„ ๋•Œ
  2. ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง๋˜์–ด props๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ
  3. ์ƒˆ๋กœ์šด props์ด ๋“ค์–ด์˜ฌ ๋•Œ
  4. shouldComponentUpdate์—์„œ true๊ฐ€ ๋ฐ˜ํ™˜๋  ๋•Œ
  5. forceUpdate๊ฐ€ ์‹คํ–‰๋  ๋•Œ

์ด ๋•Œ 1,2์˜ ๊ฒฝ์šฐ ๋ณ€๊ฒฝ์ด ์žˆ๋‹ค๋Š”๊ฑธ ๊ฐ์ง€ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์œ„์˜ Shallow Compare์ด๋‹ค. ์•„๋ž˜๋Š” ๋ฆฌ์•กํŠธ ๊ณต์‹ ๋ฌธ์„œ์—์„œ์˜ ์„ค๋ช…์ด๋‹ค. image

๋” ์ •ํ™•ํ•˜๊ฒŒ๋Š” Object.is ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์–•์€ ๋น„๊ต๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.

const [todos, setTodos] = useState([])

const updateTodos = (newTodo:string) => {
 	// 1
  setState((prev)=>{
    prev.unshift(newTodo)
    return prev
  })
  // 2
  setState((prev)=>{
    return [...prev, newTodo]
  })
}

1์˜ ๊ฒฝ์šฐ, ์ƒˆ state๋กœ ์„ค์ •๋œ ๊ฐ’์€ ๋‚ด์šฉ์ด ๋ฐ”๋€Œ์—ˆ์ง€๋งŒ ์ฐธ์กฐ๊ฐ€ ๋ฐ”๋€Œ์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ ๋ฆฌ๋ Œ๋”๋ง์ด ์ผ์–ด๋‚˜์ง€ ์•Š๋Š”๋‹ค

2์˜ ๊ฒฝ์šฐ, ์ƒˆ state๋กœ ์„ค์ •๋œ ๊ฐ’์˜ ์ฐธ์กฐ๊ฐ€ ๋ฐ”๋€Œ์—ˆ์œผ๋ฏ€๋กœ ๋ฆฌ๋ Œ๋”๋ง์ด ์ผ์–ด๋‚œ๋‹ค.

setState๋ฟ๋งŒ ์•„๋‹ˆ๋ผ

SWR์˜ mutate() ๋˜ํ•œ data๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•  ๋•Œ Shallow Compare์„ ์‚ฌ์šฉํ•œ๋‹ค(๊ณ  ์ถ”์ •๋œ๋‹ค).

๋”ฐ๋ผ์„œ ์ƒํƒœ๋ฅผ updateํ•  ๋•Œ๋Š” ๊ฐ™์€ ์ฐธ์กฐ๋ฅผ ๊ฐ€์ง„ ๊ฑธ๋กœ ์—…๋ฐ์ดํŠธํ•˜๋ฉด ์•ˆ๋œ๋‹ค!!!

์ฐธ๊ณ  ๋ฌธํ—Œ

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/is

๐Ÿฆ† Duxcord ๐Ÿฆ†

F4

ํ”„๋กœ์ ํŠธ

๊ฐœ๋ฐœ ์ผ์ง€

์Šคํ”„๋ฆฐํŠธ ๊ณ„ํš

๋ฉ˜ํ† ๋ง

๋ฐ์ผ๋ฆฌ ์Šคํฌ๋Ÿผ

๋ฐ์ผ๋ฆฌ ๊ฐœ์ธ ํšŒ๊ณ 

์œ„ํด๋ฆฌ ๊ทธ๋ฃน ํšŒ๊ณ 

์Šคํ„ฐ๋””

ํ”ผ์–ด์„ธ์…˜

Clone this wiki locally