Zustand 특징과 타입스크립트에서의 기본 사용법

Chrisko·2023년 10월 12일
0

TS, JS 라이브러리

목록 보기
1/3

Zustand 특징

  1. 상태 변경에 따른 필요 이상의 리렌더링을 억제한다.
  2. 보일러플레이트가 거의 없다.
  3. Redux Devtools로 디버깅이 가능하다.

사용법

1. state의 interface 선언

/* interface.ts */
export interface SomeStateInterface {
	someValue1: number;
	someValue2: string;
	...
	setSomeVal1: (params: number) => returnType;
	setSomeVal2: (params: string) => returnType;
	...
}

[! info] returnType이 없는 경우에는 (...) => void; 형태가 된다.


2. store 만들기

/* store.ts */
import { create } from "zustand";
import { SomeStateInterface } from "./interface";

export const useSomeState = create<SomeStateInterface>((set) => ({
	someValue1: 0,
	someValue2: "",
	...
	setSomeVal1: (params: number) => 
		set({
			someValue1: params,
		}),
	setSomeVal2: (params: string) => 
		set({
			someValue2: params,
		}),
}));

3. store 사용하기

/* App.tsx */
import { useSomeState } from "./store";

function App() {

	/* someValue1 === 0 */
	const someValue1 = useSomeState((state) => state.someValue1);
	const setSomeVal1 = useSomeState((state) => state.setSomeVal1);

	setSomeVal1(10);

	return (
		<main>
			{someValue1} // 10
		</main>
	);
}

store를 잘못 사용한 예

/* App.tsx */
function App() {
	const { someValue1, setSomeVal1 } = useSomeState((state) => state);
	...
}

구조분해 할당을 통해 store를 사용하면 안 되는 이유
구조분해 할당은 state 객체 전체를 로드하고 그 안에서 필요한 변수를 취사선택하는 구조다.
여기서 중요한 것은 "state 객체 전체 로드"인데, 이때 모든 변수가 따라오므로 불필요한 리렌더링이 무수히 일어나게 무한 렌더링 문제로 불거진다.


4. DevTools로 state 디버깅하기

Zustand는 자체 미들웨어로 DevTools를 지원하고 있다.

 

import { devtools } from "zustand/middleware";

Chrome 웹 스토어에서 Redux DevTools를 설치한 뒤 useSomeState를 아래와 같이 변경한다.

import { create } from "zustand";
import { SomeStateInterface } from "./interface";
import { devtools } from "zustand/middleware";

/* 기존에 정의한 State의 로직에서 create를 제거한다. */
const store = (set) => ({
	someValue1: 0,
	someValue2: "",
	...
	setSomeVal1: (params: number) => 
		set({
			someValue1: params,
		}),
	setSomeVal2: (params: string) => 
		set({
			someValue2: params,
		}),
});

/* devtools로 기존 state logic 변수를 wrapping한다. */
export const useSomeState = create<SomeStateInterface>(devtools(store));

/* 개발-배포 버전 분기 처리하려면 */
export const useSomeState = create<SomeStateInterface>(
	process.env.NODE_ENV === "development" ? devtools(store) : store
);

위와 같이 작성하고 Chrome - Redux DevTools를 확인하면 State를 트레이싱할 수 있다.

0개의 댓글