[React] Zustand! 간단하고 가벼운 상태관리 라이브러리

Ryomi·2025년 7월 10일
1
post-thumbnail

전역 상태관리 라이브러리 너무 어렵지 않나요? Recoil, Redux 넘 복잡해요…
최근에 정착한 간단하고 가벼운 상태관리인 Zustand에 대해 정리해봤습니다!

Zustand란?

Zustand는 독일어로 "상태(state)" 라는 뜻입니다.
React 앱에서 전역 상태를 간단하게 관리할 수 있도록 만든 가벼운 상태관리 라이브러리예요.

  • Redux보다 심플하고 코드량이 적음
  • Context API의 복잡한 Provider 트리 없이 전역 관리 가능
  • React와 잘 통합되며, 성능도 우수..!!

✅ 언제 Zustand를 써야 할까?

  • 컴포넌트 간에 공통 상태를 공유하고 싶을 때
  • Redux는 너무 무겁고 설정이 복잡할 때
  • Context API는 한계가 있을 때
  • 상태관리를 깔끔하게 하고 싶을 때

⚙️ 설치 방법

터미널에서 아래 명령어로 설치할 수 있습니다.

npm install zustand
# 또는
yarn add zustand

🧪 기본 사용법 예제

간단한 카운터 스토어를 만들어보겠습니다.

// counterStore.ts
import { create } from 'zustand'

interface CounterState {
  count: number
  increase: () => void
  decrease: () => void
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 })),
}))

컴포넌트에서 사용하기

// CounterComponent.tsx
import React from 'react'
import { useCounterStore } from './counterStore'

function CounterComponent() {
  const { count, increase, decrease } = useCounterStore()

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increase}>+1</button>
      <button onClick={decrease}>-1</button>
    </div>
  )
}

🧠 Zustand의 핵심 특징

특징설명
가벼움Redux에 비해 훨씬 작은 번들 크기
단순한 APIcreate() 하나로 상태와 액션을 모두 정의
React Context 미사용별도 Provider 필요 없음
구독 기반상태가 변경될 때 해당 컴포넌트만 리렌더링
미들웨어 확장 가능persist, devtools 등 미들웨어 추가 가능

🧩 중급 기능 예시: localStorage에 상태 저장 (persist)

import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export const useUserStore = create(
  persist(
    (set) => ({
      username: '',
      setUsername: (name: string) => set({ username: name }),
    }),
    {
      name: 'user-storage', // localStorage 키
    }
  )
)

🪄 마무리

Zustand는 러닝커브가 거의 없고, 즉시 사용 가능한 간편한 상태관리 도구라고 합니다!
프로젝트가 커질수록 복잡도가 증가하면서 상태관리를 어떻게 해야할지 고민이 많았는데, 선택기준을 명확히해서 앞으로는 zustand를 도입해보려고 합니다 ..! 화이팅

읽어주셔서 감사합니다 :D

profile
making a list, checking it twice 🐥

0개의 댓글