• Blog

  • Snippets

Introduction

June 4, 2024

Zustand

Zustand 공식문서를 참고하여 번역함.

zustand-thumbnail.jpeg

간단하고 빠르며 확장 가능한 기본 상태 관리 솔루션인 Zustand는 훅 기반의 편안한 API를 제공합니다. 이 솔루션은 번거롭거나 특정한 방법을 강요하지 않으며, 명확하고 플럭스(Flux)와 유사한 충분한 규칙성을 가지고 있습니다.

귀엽다고 무시하지 마세요, 이 상태 관리 솔루션은 강력합니다! 흔히 발생하는 문제들을 해결하기 위해 많은 시간을 투자했습니다. 예를 들어, 악명 높은 zombie child problem, React concurrency, 그리고 혼합 렌더러 간의 context loss 등을 다루었습니다. React 영역에서 이 모든 문제를 올바르게 해결하는 유일한 상태 관리 도구일지도 모릅니다.

여기에서 실시간 데모를 시도해 볼 수 있습니다.

# Installation

Zustand는 NPM 패키지로 사용 가능합니다:

Terminal

# NPM
npm install zustand
# Or, use any package manager of your choice.

# First create a store

당신의 스토어는 훅입니다! 여기에 원시값, 객체, 함수 등 무엇이든 넣을 수 있습니다. set 함수는 상태를 병합합니다.

import { create } from 'zustand'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
updateBears: (newBears) => set({ bears: newBears }),
}))

# Then bind your components, and that's it!

프로바이더 없이 어디서든 훅을 사용할 수 있습니다. 선택한 상태가 변경되면 해당 상태를 사용하는 컴포넌트가 자동으로 다시 렌더링됩니다.

function BearCounter() {
const bears = useStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}