Immer은 불변성 관리를 조금 더 쉽게 해주는 자바스크립트 라이브러리다.
const baseState = [
{
title: "Learn TypeScript",
done: true
},
{
title: "Try Immer",
done: false
}
]
const nextState = baseState.slice() // shallow clone the array
nextState[1] = {
// replace element 1...
...nextState[1], // with a shallow clone of element 1
done: true // ...combined with the desired update
}
// since nextState was freshly cloned, using push is safe here,
// but doing the same thing at any arbitrary time in the future would
// violate the immutability principles and introduce a bug!
nextState.push({title: "Tweet about it"})
immer가 없이는 이렇게 불변성을 지켜줘야 하는 것을
import produce from "immer"
const nextState = produce(baseState, draft => {
draft[1].done = true
draft.push({title: "Tweet about it"})
})
이런 식으로 깔끔하게 기존의 코드를 변경하는 방식으로 동일한 결과를 얻을 수 있다.
Immer은 현재값의 proxy인 draft에 변화(mutation)를 적용하고 이 변화들을 적용한 draft를 통해 nextState를 produce한다.
이를 통해서 불변성을 지키되 그냥 코드를 수정하는 방식으로도 할 수 있게 된다.
produce(currentState, recipe: (draftState) => void): nextState
위에서 말한 동작을 이 produce 함수를 통해 할 수 있다.
currentState에서는 원래 값, recipe은 draft 값들을 어떻게 바꿀 것인가를 의미한다.
이를 통해서 currentState는 건드리지 않고, 새로운 값을 도출해낼수 있는 것이다.
ES6 이후의 자바스크립트에 능숙하다면 Immer를 사용하지 않더라도 충분히 동일한 동작을 구현할 수 있지만, Immer의 진짜 장점은 가독성이 훨씬 좋다진다는것이 아닐까 생각한다.
'TIL' 카테고리의 다른 글
| TIL 2022-04-19 Svelte Tutorial 1~4 (0) | 2022.04.19 |
|---|---|
| TIL 2022-04-18 Svelte (0) | 2022.04.18 |
| 2022-04-04 Map, WeakMap, Array.from (0) | 2022.04.04 |
| TIL 2022-03-23 HTML 요소 (0) | 2022.03.23 |
| TIL 2022-03-22 git 원격 브랜치 가져오기, commit --amend, stash (0) | 2022.03.22 |
