[React] React 상태관리 시리즈 - 1 - Zustand

Date:

카테고리:

태그:

1. 가볍고 편한 상태관리 라이브러리 Zustand

1. Redux의 대안의 필요성

부트캠프에서 같이 프로젝트를 하면서 TS, Redux, Redux Toolkit 을 사용해 보았다 전역적인 상태관리를 해준다는 점은 편했지만, 대신 하나의 변수를 사용하기 위해 작성해야 할 코드가 많은 것은 아쉬웠다 그래서 프로젝트가 끝나면 Redux 외에 다른 상태관리 라이브러리를 경험해 보기로 생각했다

2. Zustand 설치

  • Zustand 설치

    npm i zustand
    

3. Zustand state 관리

  • Zustand 저장소 만들기

    // app.js
    
    // 상단에 create 가져오기
    import create from "zustand";
    
    // 스토어를 선언하고 원하는 변수 넣기
    const useStore = create(() => ({
      count: 0,
      increase() {
        set((state) => ({ count: state.count + 1 }));
      },
    }));
    
  • Zustand state 가져오기

    const { count } = useStore();
    

4. Zustand state 수정

  • Zustand 변수 수정

    useStore.setState({ count: count - 1 });
    

5. ajax 요청

  • Zustand로 ajax 요청하기

    // app.js
    
    // ajax 요청하는 코드
    const useStore = create(() => ({
      count: 0,
      increase() {
        set((state) => ({ count: state.count + 1 }));
      },
      async ajaxFunc() {
        const res = await fetch("URL");
        console.log(await res.json());
      },
    }));
    

6. 총평

확실히 zustand는 redux 대비 장점이 있었다

  • 초기 셋팅이 더 쉬움 (<provider>로 감싸기 등)
  • 문법이 더 짧고 간편함
  • bundle 크기가 작음
  • npm 다운로드 수가 높음(recoil, jotal 대비)

zustand 외에도 다른 라이브러리들도 둘러 보면서 장단점을 비교해보아야 겠다

참고블로그 - 1

참고블로그 - 2

React 카테고리 내 다른 글 보러가기

댓글 남기기