REACT

Zustand란?

user-anonymous 2024. 2. 5. 23:55
728x90

Zustand는 리액트에서 사용할 수 있는 가벼운 상태 관리 라이브러리다. 단순한 API 기반으로 작동하며, create 함수 하나만으로도 커스텀 훅을 생성할 수 있어 사용법이 간결하다.

Redux와 비교했을 때 불필요한 설정이 없고, 모듈화도 편해서 최근 프로젝트에 종종 사용하게 된다.


Redux와의 차이

Redux는 상태 관리를 위해 createStore, combineReducers, Reducer 등을 설정해야 한다.

import { combineReducers } from "redux";
import nameTag from "./nameTag";
import location from "./location";
import excel from "./excelData";

const rootReducer = combineReducers({
  nameTag,
  location,
  excel
});

export default rootReducer;

상당히 복잡하고 boilerplate 코드가 많다.

반면 Zustand는 아래처럼 간단하게 create 함수를 이용해 상태를 정의하고 사용할 수 있다.


Zustand 설치

# yarn 사용 시
yarn add zustand

# npm 사용 시
npm install zustand

기본 사용법

import { create } from "zustand";

const useChangeText = create((set) => ({
  text: "happy",
  changeToSad: () => set(() => ({ text: "sad" })),
}));
  • useChangeText는 우리가 직접 만든 커스텀 훅이다.
  • text: 상태 값
  • changeToSad: 상태를 변경하는 액션 함수

컴포넌트에서 아래와 같이 상태를 가져오거나 변경할 수 있다.

상태 가져오기

const ShowText = () => {
  const displayText = useChangeText((state) => state.text);
  return <div>{displayText}</div>;
};
상태 변경하기
const ChangeText = () => {
  const chgText = useChangeText((state) => state.changeToSad);
  return (
    <button onClick={chgText}>슬픔이</button>
  );
};

만약 A, B 두 컴포넌트에서 같은 상태를 사용 중이라면, B 컴포넌트에서 상태가 변경되면 A에서도 자동으로 반영된다.

전역 상태 관리가 필요한 상황에서 유용하게 쓸 수 있다.


마무리하며

Zustand는 개인적으로 작고 빠른 상태 관리 도구로 매우 만족스럽게 사용하고 있다. 설정도 간단하고, 커스텀 훅 기반이기 때문에 리액트스러운 코드 작성을 도와준다. 간단한 프로젝트에서는 Redux보다 훨씬 가볍고 직관적이어서 앞으로도 자주 사용하게 될 것 같다.

728x90
반응형