01. Zustand로 상태관리 하기

2024. 10. 6. 19:35·스터디/사이드 프로젝트

지금까지 리액트 프로젝트는 2번 정도 진행 했었는데 상태 관리 라이브러리를 적용해 본 경험이 없어서

이번 프로젝트에서는 zustand를 활용하여 상태관리를 해보고자 한다.

 


https://zustand.docs.pmnd.rs/getting-started/introduction

Zustand란?

  • React 상태 관리 라이브러리
  • hook를 기반으로 한 간결하고 직관적인 API를 제공하며, 전역 상태 관리를 간단하게 구현할 수 있게 해준다.

Persist와 같이 사용하기

Zustand의 미들웨어 중 하나로, 상태를 브라우저의 저장소에 저장할 수 있게 해준다. 이를 통해 페이지를 새로고침하거나 브라우저를 닫고 다시 열어도 상태가 유지되도록 할 수 있다.

 

Zustand 설치

npm install zustand

 

src/store/authStore.ts 파일 생성

  • zustand import
  • 인터페이스 정의 : 스토어의 상태와 액션 타입을 명시
interface UserInfo {
    email: string;
    nickname: string;
}

interface AuthState {
    isLoggedIn: boolean;
    userInfo: UserInfo | null;
    errorMessage: string;
    login: (email: string, password: string) => Promise<void>;
    logout: () => void;
}
  • 스토어 생성
    • create : 스토어 생성
    • persist : 상태를 localStorage에 저장할 수 있게 설정
    • 상태 초기값 설정
    • 함수 설정
    • name : 상태 저장할 키 값
    • storage : localStorage 사용하도록 설정
const useAuthStore = create<AuthState>()(
    persist(
        (set) => ({
            isLoggedIn: false,
            userInfo: null,
            errorMessage: '',
            login: async (email, password) => {
                const user = await gf_login(email, password);
                if (user) {
                    set({ isLoggedIn: true, userInfo: user, errorMessage: '' });
                } else {
                    set({ isLoggedIn: false, userInfo: null, errorMessage: '로그인 정보가 올바르지 않습니다.' });
                }
            },
            logout: () => set({ isLoggedIn: false, userInfo: null, errorMessage: '' }),
        }),
        {
            name: 'loginUserInfo', // 저장할 키
            storage: createJSONStorage(() => localStorage),
        }
    )
);

무한 루프 오류 발생

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

 

zustand로 로그인 기능 연결 후 메인으로 넘어오니 무한 루프 오류가 발생했다.

원인

 const { userInfo, isLoggedIn } = useAuthStore(state => ({
     userInfo: state.userInfo,
     isLoggedIn: state.isLoggedIn,
}));

useAuthStore를 호출할 때, 상태의 일부가 변경되면 해당 컴포넌트는 리렌더링되는데, 두 상태를 함께 destructuring 하면서 이 상태들이 각각 업데이트될 때마다 리렌더링이 발생하면서 무한 루프가 발생한 것 같다.

해결

const userInfo = useAuthStore(state => state.userInfo);
const isLoggedIn = useAuthStore(state => state.isLoggedIn);

각 상태를 별도의 useAuthStore 호출로 구독하도록 코드를 수정했다.

'스터디 > 사이드 프로젝트' 카테고리의 다른 글

01. 포트폴리오 사이트 1차 완료  (2) 2024.10.18
00. 포트폴리오 사이트의 시작  (3) 2024.10.15
03. Supabase 연동  (0) 2024.10.11
02. Vercel로 배포하기  (0) 2024.10.07
00. 사이드 프로젝트 세팅  (0) 2024.10.05
'스터디/사이드 프로젝트' 카테고리의 다른 글
  • 00. 포트폴리오 사이트의 시작
  • 03. Supabase 연동
  • 02. Vercel로 배포하기
  • 00. 사이드 프로젝트 세팅
개발자 화진
개발자 화진
https://github.com/HwajinLee3114
  • 개발자 화진
    lhjin.log
    개발자 화진
  • 전체
    오늘
    어제
    • 분류 전체보기 (31)
      • 개발 (10)
        • FE (9)
        • BE (0)
      • Algorithm (0)
      • 기술면접 (4)
      • 스터디 (14)
        • 사이드 프로젝트 (7)
        • Udemy) NextJS 15 & React (3)
        • Udemy) TypeScript with Reac.. (1)
      • ETC (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    모노레포
    React
    코딩앙마
    오블완
    멀티레포
    lazy loading
    프론트엔드
    javascript
    아키텍처
    사이드프로젝트
    fe
    pnpm
    Zustand
    프론트엔드 아키텍처
    udemy
    multirepo
    NextJS
    자바스크립트
    유데미 스터디
    supabase
    Frontend
    유데미 러닝크루
    Next.js
    인프런
    티스토리챌린지
    유데미
    유데미 코리아
    Typescript
    ThemeProvider
    vercel
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
개발자 화진
01. Zustand로 상태관리 하기
상단으로

티스토리툴바