๊ฐœ๋ฐœ/react

react. state๊ฐ€ immutableํ•ด์•ผ ํ•˜๋Š” ์ด์œ 

ttoance 2023. 8. 15. 07:35

๐Ÿ”ฑ ์ˆ˜์—… https://nomadcoders.co/react-masterclass/lobby ์„ ๋“ฃ๋‹ค๊ฐ€ 6.14, 6.15์žฅ immutability part ๋ฅผ ๋“ฃ๋‹ค๊ฐ€ ์•„๋ž˜ slice ํ†ตํ•ด์„œ ๊ฐ’์„ ๊ต์ฒดํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ•˜๋Š” ๊ฒƒ์„ ๋ณด๊ณ  ์™œ state๊ฐ€ immutable ํ•ด์•ผ ํ•˜๋Š”์ง€ ์ฐพ์•„๋ณด์•˜๋‹ค. 

    setToDos((oldTodos) => {
        const targetIndex = oldTodos.findIndex(toDo => toDo.id === id);
        const oldTodo = oldTodos[targetIndex];
        const newTodo = {text, id, category: name as any};

        return [
            ...oldTodos.slice(0, targetIndex),
            newTodo,
            ...oldTodos.slice(targetIndex + 1),
        ];    
    })

 

 

1. immutable์˜ ์˜๋ฏธ 

- ๋ฐ์ดํ„ฐ๊ฐ€ ์ ˆ๋Œ€๋กœ ๋ฐ”๋€Œ์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์•„๋‹ˆ๋‹ค. 

- ์˜ˆ๋ฅผ ๋“ค์–ด, ๋ฐฐ์—ด์„ mutateํ•œ๋‹ค ํ–ˆ์„๋•Œ, 

> ์›๋ž˜ ๋ฐฐ์—ด์˜ ๋ณต์‚ฌ๋ณธ์„ ๋งŒ๋“ ๋‹ค. 

> ๋ณต์‚ฌ๋ณธ์— ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ์ ์šฉํ•œ๋‹ค. 

> ์›๋ž˜ ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝ๋œ ๋ณต์‚ฌ๋ณธ์œผ๋กœ ๊ต์ฒดํ•œ๋‹ค. 

 

2. ์™œ react๊ฐ€ immutableํ•œ์ง€ ?

- ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ re-rendering ๋  ๋•Œ new value ๊ฐ€ ํ•„์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ 

> ๋งŒ์•ฝ 3๊ฐœ์˜ ๊ฐ’์ด ์žˆ๋Š” array์—์„œ 4๋ฒˆ์งธ ๊ฐ’์„ ๋„ฃ๋Š”๋‹ค๊ณ  ํ•ด์„œ, reference๊ฐ€ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๋Š”๋‹ค. 

 

์ฐธ๊ณ  ๋ฌธํ—Œ > 

https://reacttraining.com/blog/state-in-react-is-immutable

 

State in React is Immutable

tldr; When you set state in React, a new value must be passed or React will bail-out and not *re-render your component. React uses something similar to === to compare the old and new state to see if they're the same. They say in docs they use Object.is() i

reacttraining.com

https://scoring.tistory.com/entry/React-%EB%A6%AC%EC%95%A1%ED%8A%B8%EC%97%90%EC%84%9C-%EB%B6%88%EB%B3%80%EC%84%B1%EC%9D%84-%EC%A7%80%ED%82%A4%EB%8A%94-%EC%9D%B4%EC%9C%A0

 

[React] ๋ฆฌ์•กํŠธ์—์„œ ๋ถˆ๋ณ€์„ฑ์„ ์ง€ํ‚ค๋Š” ์ด์œ 

๋ฆฌ์•กํŠธ์—์„œ ๋ถˆ๋ณ€์„ฑ์„ ์ง€ํ‚ค๋Š” ์ด์œ  ๋ถˆ๋ณ€์„ฑ์ด๋ž€ ์‚ฌ์ „์  ์˜๋ฏธ๋กœ ๊ฐ’์ด๋‚˜ ์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. React๊ฐ€ ๋ถˆ๋ณ€์„ฑ์„ ์ง€ํ‚ค๋Š” ์ด์œ ๋Š” ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ re-rendering ๋˜๊ฑฐ๋‚˜ State, Props ์— ๋ณ€ํ™”

scoring.tistory.com

 

๋ฐ˜์‘ํ˜•