-
[리액트를 다루는 기술] immer프로그래밍/React 2023. 6. 20. 00:09
immer은 언제 쓰이는가?
spread연산자만으로는 깊은복사가 나왔을 때 제대로 대처하기 어렵다. 그래서 써야하는 게 이 immer라이브러리이다. 또한 전개연산자를 자주 사용하게 되면 가독성도 좋지 않아서 이러한 상황에서는 immer을 적극 활용해 보자. (깊은복사의 방법에서 immer함수가 쓰인다)
import produce from 'immer'; const nextState = produce(originalState, draft => { darft.somewhere.deep.inside = 5 //바꾸고싶은 값 });
라이브러리이기때문에 따로 설치해야 함 yarn add immer
이 함수는 불변성 신경 안쓰는거 같아보여도 다 관리하는 게 특징임
원래 spread연산자 쓴 자리에 produce 갈아 끼우기만 하면 됨 ㅈㄴ 간단함
사용한다 해서 다 좋은게 아님 가끔은 filter나 다른 함수들이 더 좋을 때가 있으니 적절히 시기 맞춰서 쓰길
그리고 push 나 pop같은거 쓸 수 있다 왜냐? produce로 새로운 객체 만들었으니 여기다가 해도 ㄱㅊ다는 말인 듯
useState의 함수형 업데이트와 함께 쓰는거에서 그냥 data와 draft 두개의 인자를 받았던 걸 draft만 받는데 이게 뭐 useState를 쓴건가?? 뭐지?
produce 함수
이 함수는 2개의 인자르 받는데 첫번쨰 인자는 수정하고 싶은 상태를 받고, 두번째 인자는 바꿀 로직이 담긴 함수를 받는다.
이 함수를 이용하면 불변성을 유지한 채 새로운 함수를 만들어 내니깐 아주 적절하게 사용해야겠다.
불변성을 유지한다
기타 에러사항
import 하고 중괄호 있는거랑 없는거랑 차이가 뭐지??? 한개일 때도 쓰는 경우 많던데
아니 없으니깐 준내 에러 뜨는데 xport 'default' (imported as 'produce') was not found in 'immer' 이런식으로 꼭 있어야하나보다'프로그래밍 > React' 카테고리의 다른 글
[리액트 알쓸신잡] Hook - 1 - useMemo VS useCallback (0) 2023.06.22 [리액트 다루는 기술] 리덕스 작동원리 && 기초 (0) 2023.06.21 [리액트를 다루는 기술] 컴포넌트의 반복 (0) 2023.06.18 [리액트를 다루는 기술] Hook (useState, Effect, Reducer, Ref) 1편 (0) 2023.06.18 [리액트를 다루는 기술] 컴포넌트 (0) 2023.06.18