-
24. Immer라이브러리와 불변성 관리Java Script & Type Script 2023. 1. 11. 10:58728x90
리액트에서 배열이나 객체를 업데이트해야 할 때에는 직접적인 수정을 하면 안되고 불변성을 지켜주면서 업데이트를 해야한다.
const object = { a: 1, b: 2 }; const nextObject = { ...object, b: 3 };
위와 같이 spread연산자를 이용해서 새로운 객체를 만들어준다.
배열 또한 마찬가지로 push, splice등의 함수를 사용해 직접 수정하면 안되고, concat, filter, map등의 함수를 사용해야 한다.
대부분의 경우 spread연산자 또는 배열 내장함수를 사용하는건 어렵지 않지만 데이터 구조가 조금 까다로워지면 불변성을 지키면서 새로운 데이터를 생성하는 코드가 복잡해진다.
Immer라는 라이브러리를 사용하면 불변성을 유지하며 간결한 코드로 필요한 내용을 업데이트할 수 있다.
posts배열 내 id가 1인 post객체를 찾아서 comments에 새로운 댓글객체를 추가해줘야 하는 경우
const nextState = { ...state, posts: state.posts.map(post => post.id === 1 ? { ...post, comments: post.comments.concat({ id: 3, text: '새로운 댓글' }) } : post ) };
위의 코드는 immer를 사용하지 않은 코드이다. 불변성을 유지하기 위해 코드가 꽤 복잡하다.
const nextState = produce(state, draft => { const post = draft.posts.find(post => post.id === 1); post.comments.push({ id: 3, text: '와 정말 쉽다!' }); });
이 코드는 immer를 이용. 확실히 간결해졌다.
🐹 Immer를 사용하면 우리가 상태를 업데이트할 때 불변성을 신경쓰지 않으면서 업데이트를 해주면 immer가 불변성 관리를 대신 해준다.
🐹 Immer의 첫번째 파라미터에 수정하고싶은 상태, 두번째 파라미터에는 어떻게 업데이트하고싶은지 정의하는 함수를 넣으면 된다. (두 번째 파라미터의 함수에서는 불변성에 대해 신경쓰지 않고 업데이트해도 불변성이 유지된다. )
728x90'Java Script & Type Script' 카테고리의 다른 글
26. [React] 태그 내 스타일속성 넣기, 별점 구현하기 (0) 2023.01.31 25. [React] 뼈갈넣 회원가입 유효성 검사 (0) 2023.01.28 23.[리액트] 리덕스 툴킷, JSON 서버, 콜백 함수로 비동기 처리 방식의 문제점 해결하기, PROMISE (0) 2023.01.11 22.[React 팀과제 정리] Promise , TDZ, Thunk (0) 2023.01.09 21.[React, JS] JS 비동기처리와 Promise, async, await (0) 2023.01.07