immer 도입하기

제이밍·2021년 8월 12일
1
post-thumbnail

immer ?

불변성을 지키다 보면 아래와 같이 복잡한 코드를 작성해야 할 상황이 온다
하지만 이를 도와주기 위한 npm 으로 immer 이라는 라이브러리가 있다.

react, redux 등에서 사용 가능하다. (hook 버전 -> use-immer)

사용방법

이전상태를 액션을 통해 다음 상태로 만들어 내는 함수 (단, 불변성은 비키면서)

npm i immer

import produce from 'immer';
기본형태 reducer 안에 다음과 같이 작성한다.

const reducer = (state = initialPostState, action: AnyAction) => {
  return produce(state, (draft)=>{
    //state 이름이 draft로 바뀐다
    draft
	... 이전 코드들은 이 곳으로 전부 이동!
      
     default:
        break;
  });
    

자바스크립트의 불변성을 지키기위해 어쩔수 없이 아래와 같이 길어진 코드를 immer을 사용함으로써 아래코드처럼 단축시켜 줄 수 있다.

Before

   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,
         };
     }

After

  case ADD_COMMENT_SUCCESS: {
        const post = draft.mainPosts.find((v: any) => v.id === action.data.postId);
        post.Comments.unshift(dummyComment(action.data.content));
        draft.addCommentLoading = false;
        draft.addCommentDone = true;
        break;
      }

Before

     case ADD_POST_TO_ME:
      return {
        ...state,
        me: {
          ...state.me,
          Posts: [{id: action.data},...state.me.Posts],
        },
      };

After

   case ADD_POST_TO_ME:
        draft.me.Posts.unshift({ id: action.data });
        break;

불변성을 신경쓰지 않고 복잡한 코드를 위 처럼 간단하게 줄여 사용할 수 있다.
가독성도 좋아지고 불변성을 지키느라 생각해야할 여러가지 문제점들을 내려 놓을 수 있게 된다.

깃을 보다가 웃긴 레파지토리를 발견했다

https://github.com/kelseyhightower/nocode

제목은 nocode

No code is the best way to write secure and reliable applications.
코드가 없는것은 가장 안정적이고 안전한 애플리케이션을 만드는 가장 최고의 방법이다.

**1. Getting Started**
Start by not writing any code.
코드를 작성하지 않고 시작하십시오.

This is just an example application, but imagine it doing anything you want.
Adding new features is easy too:
이것은 예제 응용 프로그램이지만 원하는 모든 작업을 수행한다고 상상해보십시오. 새로운 기능을 추가하는 것도 쉽습니다.

The possibilities are endless.
가능성은 무한합니다.

**2. Building the Application**
Now that you have not done anything it's time to build your application
이제 아무 것도 하지 않았으므로 애플리케이션을 빌드할 시간입니다. (빌드 하지 말아라)

**3. Deploying**
While you still have not done anything it's time to deploy your application.
By running the following command you can deploy your application absolutely 
nowhere.
아직 아무것도 하지 않았지만 애플리케이션을 배포할 시간입니다.
다음 명령을 실행하면 애플리케이션을 아무데도 배포할 수 없습니다.

간단합니다. 그리고 애플리케이션을 확장할 때 해야 할 일은 다음과 같습니다.

**4.Contributing**
You don't.

당신은 하지 않습니다.
profile
모르는것은 그때그때 기록하기

0개의 댓글