immer란
- 불변성을 유지하면서도 쉽게 객체를 수정할 수 있는 라이브러리
- 객체의 상태를 업데이트할 때, 기존 객체를 직접 수정하는 대신, 새로운 객체를 생성하여 수정하는 방식을 사용
- 상태 업데이트를 위한 코드가 더욱 간결하고 가독성이 높아지며, 불변성을 유지하면서도 객체를 쉽게 수정할 수 있다. 또한 immer는 Redux와 함께 사용할 때, Redux의 불변성 규칙을 보다 쉽게 지키도록 도와준다.
immer 사용방법
- npm i immer
- import produce from "immer";를 해주고 사용하면 된다
redux - immer 예시
case ADD_COMMENT_SUCCESS: {
const postIndex = state.mainPosts.findIndex((v) => v.id === action.data.postId);
const post = { ...state.mainPosts[postIndex] };
post.Comments = [dummyComment(action.data.content), ...post.Comments];
const mainPosts = [...state.mainPosts];
mainPosts[postIndex] = post;
return {
...state,
mainPosts,
addCommentLoading: false,
addCommentDone: true,
};
}
- immer에서 produce,draft를 사용한 reducer 코드
const reducer = (state = initialState, action) => produce(state, (draft) => {
switch (action.type) {
case ADD_COMMENT_SUCCESS: {
const post = draft.mainPosts.find((v) => v.id === action.data.postId);
post.Comments.unshift(dummyComment(action.data.content));
draft.addCommentLoading = false;
draft.addCommentDone = true;
break;
}
}