Immer

미숙한 초보 코딩.Js·2019년 10월 26일
0

Technical

목록 보기
3/6

immer를 사용하면 불변성을 해치는 코드를 작성해도 대신 불변성 유지를 해준다. (라이브러리)


import produce from 'immer'

const state = {
	number: 1,
  	default : 2
}
// produce ( 기존값, 수정 하려는 값 )

const nextSTate = produce( state, draft => {
	draft.number += 1;
})

// nextState => { number: 2, default : 2 };



const array = [
  { id : 1, text : 'apple' },
  { id : 2, text : 'samsung' },
  { id : 3, text : 'lg' } 
]

const nextArray = produce(array, draft => {
	draft.push({ id : 4, text : 'hahahaha' });
    draft[0].text = draft[0].text + ' MacBook';
})
/*
nextArray => 
  { id : 1, text : 'apple MacBook' },
  { id : 2, text : 'samsung' },
  { id : 3, text : 'lg' },
  { id : 4, text : 'hahahaha' }
*/


불변성을 지키면서 값을 변경 시키고 수정 할 수 있다.

useState를 사용할때 setState에서 객체 형식을 관리학 까다로울때 produce를 이용해도 좋다.


setState(
	produce( draft => {
    	draft.done = !draft.done;
    })
)

// 첫번째에 draft 를 넣어 사용하면 업데이트 처럼 사용할 수있다.
profile
힘들땐 블로그 하나더 적자!!![ Suyang ]

0개의 댓글