immer 라이브러리

채희태·2022년 9월 25일
0

immer?

react는 불변성을 지키며 코딩을 해야 한다.
하지만 불변성을 지키며 코딩을 하는 것은 매우 번거롭고 복잡하다.
immer 라이브러리는 이러한 불변성을 알아서 지키며 다음 상태로 만들어준다.


immer 사용해보기

immer 설치
npm i immer

immer의 형태는 다음과 같다.

import produce from 'immer'
const nextState = (originalState, (draft) => {})

originalState는 이 전 상태 값이 들어가며
draft로 새로운 객체를 생성해준다.

immer로 새로운 객체를 다음과 같이 만들 수 있다.

people의 id가 2인 객체의 detail배열에 성별 정보를 넣어준다.

const info = {
  people = [
    {
	  id: 1,
  	  name: '이순신',
    },
    {
      id: 2,
      name: '홍길동',
      detail: [
        {
          job: 'student',
      	  city: 'seoul',
      	  number: 1111-1111,
        },
      ],
    },
  ],
}

//immer를 사용하지 않을 경우
const nextState = {
  ...info,
  info.people.map((person) => (
    person.id === 2 
      ?  {
      ...person,
      detail: person.detail.concat({ sex: 'mail' }),
    },
      : person
  )),
}
  
//immer를 사용할 경우
import produce from 'immer'

const nextState = produce(info, (draft) => {
  const person = draft.people.find(person => person.id === 2)
  person.detail.push({ sex: 'mail' })
})

immer를 사용하여 깔끔한 코드를 만들었다.
불변성을 지키지 않아도 되므로 push로 배열에 객체를 추가하였다.

produce로 nextState를 만들어 준다.
기존 state인 info를 draft를 이용해 바꿔준다.

리듀서에서 immer 사용해보기

해당 포스트를 제거
해당 포스트에 코멘트 추가

import produce from 'immer'

const initialState = {
  posts: [
    {
      id: 1,
      comments: [
        {
          id: 1
        },
      ],
    },
  ],
}

const reducer = (state = initialState, action) => {
  return produce(state, (draft) => {
    switch(action.type) {
      case REMOVE_POST:
        draft.posts = draft.posts.filter(post => (
          post.id !== action.data.id
        ))
        break;
      case ADD_COMMENT:
        const postToCommet = draft.posts.find(post => (
          post.id === action.data.id
        ))
        postToComment.unShift(action.data.comment)
        break;
      default:
        state;
    }
  })
}

제거 기능을 구현할 땐 불변성을 지키지 않는 것이 좋다.
splice의 경우 index를 구해야 하므로 filter가 좋다.

리듀서의 case 끝 맺음은 break를 해준다.

profile
기록, 공부, 활용

0개의 댓글