[ Zustand ] 1. 시작하기

angie·2023년 1월 18일
0

1. Zustand 시작하기

1. Zustand?

  • Zustand : 독일어로 ‘상태’라는 뜻

A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy API based on hooks, isn't boilerplatey or opinionated.
간단한 Flux 원칙을 사용하는 작고 빠르고 확장 가능한 상태 관리 솔루션

Flux 패턴

MVC 패턴을 보완하는 프론트엔드 디자인 패턴

상태를 변경하고자 한다면 Action을 만들어 Dispatcher에 전달하면 Dispatcher가 Action에 따라 Store(Model)의 데이터를 변경하고 그 변경사항을 View에 반영하는 단방향 흐름

Context API의 문제점

부모 컴포넌트 쪽에 Context.Provider 컴포넌트를 선언하고 Context로 전달되는 값이 변경될 때 해당 Context를 사용하는 모든 자손 컴포넌트는 리랜더링된다.

Redux와 비교한 Zustand의 장점

  • 간단하고 편향적이지 않다.(범용성)
  • 훅을 기반으로 함
  • 컨텍스트 provider로 앱을 감쌀 필요가 없다.
  • 렌더를 발생시키지 않으면서 컴포넌트에 일시적으로 상태 변화를 줄 수 있다.

Context와 비교한 Zustand의 장점

  • 보일러플레이트가 감소
  • 변경 시에만 컴포넌트를 렌더링
  • 중앙화된 Action 기반의 상태 관리

2. Zustand 사용법

1) 설치

npm install zustand # or yarn add zustand

2) store 생성

import { create } from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))
  • Zustand의 store는 hook이다.
  • 원시값, 객체, 함수 등 어떤 자료형도 넣을 수 있다.
  • set함수는 상태를 병합한다.

3) store 사용

function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} around here ...</h1>
}

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}
  • Provider를 사용하지 않고 hook을 어디서든 사용할 수 있다.
  • state를 사용하면 컴포넌트는 state 변화 시 재렌더된다.

방법1. select 함수 사용하여 import

// #1 select 함수를 사용해 import 하여 사용하기
const isLogin = useStore((state) => state.isLogin);

방법2. 구조분해 할당

// #2 구조분해 할당을 통해 가져오기 
const { isLogin } = useStore();

4) Devtools를 사용한 Debugging

먼저 Chrome 웹 스토어에서 Redux DevTools를 설치한 뒤, Zustand가 지원하는 Middleware인 Devtools를 사용한다.

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

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

const useStore = create(devtools(store))

export default useStore
  • 생성한 store를 devtools를 import한 후 연결해준다.
profile
better than more

0개의 댓글