React

[React] Zustand 란? 사용법 State 상태 관리

차노도리 2023. 4. 18. 17:13

Zustand

  • 상태 관리 라이브러리
  • 보일러 플레이트가 거의 없다.
  • 다른 상태 관리 라이브러리 보다 사용이 쉽다.
  • Debugging도 용의하다. ex) Redux Devtools

Zustand 설치 

npm install zustand

yarn install zustand

 

Zustand 생성

- 예시 로그인 에러 정보를 담는 zustand

import create from 'zustand';


export type CodeEnumsMemberType = 'ANY' | 'CORPORATION' | 'FRANCHISE' | 'NONE' | 'PERSONAL';
export type SocialLoginType = 'APPLE' | 'FACEBOOK' | 'GOOGLE' | 'KAKAO' | 'NAVER' | '';

export interface LoginErrorInfo {
  id: string;
  encryptedMemberId: string;
  redirectUrl: string;
  memberType: CodeEnumsMemberType;
  snsType: SocialLoginType;
  name?: string;
  errorCode?: string;
  timestamp?: number;
}

export interface LoginErrorInfoStoreProps {
  loginErrorInfo: LoginErrorInfo;
  setLoginErrorInfo: (loginerrorInfo: Partial<LoginErrorInfo>) => void;
  resetLognErrorInfo: () => void;
}

const initState: LoginErrorInfo = {
  id: '',
  encryptedMemberId: '',
  redirectUrl: '/',
  memberType: 'PERSONAL',
  snsType: '',
  name: '',
  errorCode: '',
  timestamp: 0,
};

const useLoginErrorStore = create<LoginErrorInfoStoreProps>(set => ({
  loginErrorInfo: initState,
  setLoginErrorInfo: errorInfo => {
    set(state => ({
      ...state,
      loginErrorInfo: { ...initState, ...errorInfo },
    }));
  },
  resetLognErrorInfo: () => {
    set(state => ({
      ...state,
      loginErrorInfo: initState,
    }));
  },
}));

export { useLoginErrorStore };

Zustand 사용

const { loginErrorInfo, setLoginErrorInfo, resetLognErrorInfo } = useLoginErrorStore();

console.log('loginErrorInfo',loginErrorInfo);

resetLognErrorInfo();

setLoginErrorInfo({ errorCode, timestamp });