Immer 톺아보기

Jake·2022년 8월 29일
0

immer

목록 보기
1/1
post-thumbnail

Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.

immer를 사용하는 이유

자바스크립트의 객체는 다른 객체를 프로퍼티로 가질 수 있다.
구조가 간단한 객체의 경우 얕은복사
1. Spread Syntax ...
2. Object.assign(target,source) 메서드로 해결할 수 있지만 구조가 복잡한 객체의 경우 이런 방식의 복사는 문제를 일으킨다.
immer는 깊은복사를 손 쉽게 도와주는 도구이다.

How to use *Produce

immer라이브러리가 제공하는 특수함수.

import produce from 'immer';
produce(baseState , recipe: (draft조작 코드)) => nextState // returned state

특징

  1. baseState를 파라미터로 받는다(해당객체는 변하지않음)
  2. 원하는 모든 변화는 draft(원본객체:currentState의 프록시 객체)를 통해 이뤄진다.
  3. recipe는 모든 자바스크립트 API를 활용할 수 있다.

*프록시객체

Terminology

produce(baseState, recipe: (draftState) => void): nextState

  • (base)state: 'produce'함수로 넘겨질 불변객체

  • recipe : 'produce'의 2nd 파라미터, baseState가 어떻게 변형될지 포착하는 콜백함수.

  • draft: baseState의 *프록시객체
    //draft는 아무 명칭으로 변경할 수 있으며,
    해당 객체를 조작하여 nextState를 반환한다.

[예제1]

import produce from "immer"

const baseState = [
    {
        title: "Learn TypeScript",
        done: true
    },
    {
        title: "Try Immer",
        done: false
    }
]

const nextState = produce(baseState, draftState => {
    draftState.push({title: "Tweet about it"})
    draftState[1].done = true
})



[예제2]

import produce from "immer"

function toggleTodo(state, id) {
    return produce(state, draft => {
        const todo = draft.find(todo => todo.id === id)
        todo.done = !todo.done
    })
}

const baseState = [
    {
        id: "JavaScript",
        title: "Learn TypeScript",
        done: true
    },
    {
        id: "Immer",
        title: "Try Immer",
        done: false
    }
]

const nextState = toggleTodo(baseState, "Immer")


/*
*arr.find( item:함수호출요소 , index:해당요소인덱스 , array: arr)
//find 메서드는 함수의 반환 값을 true로 만드는 단 하나의 요소를 찾아서 그 값을 반환한다.
//find메서드엔 일반적으로 item 파라미터만을 넘긴다. (idx,arr는 보통 생략) 
*/
profile
young하고 MZ해요

0개의 댓글