본문 바로가기
Front-End/Next.js(React | Ts|Js)

React 상태관리 라이브러리 - Zustand 설명 및 사용법

by cocogugu 2024. 5. 14.
반응형

 

사내에서 새롭게 시작하는 프로젝트에서 새로운 상태관리 라이브러리를 써보자고 해서 조사하다가 도입하게된 "Zustand"에 대해서 소개 하겠습니다.

 

Zustand

- Zustand는 독일어로 "상태"라는 뜻인데 "Jotai"라는 상태 라이브러리를 만든 개발자들이 만든 상태관리 라이브러리로 알려져 있습니다. 

 

 Zustand의 가장 큰 장점은 매우 쉽다는 것입니다. 보일러플레이트 코드는 거의 없고 Redux Devtools를 사용할 수 있어서 Debugging도 용이하게 할 수 있다.

 

Zustand 사용법

1. Zustand 다운로드

 npm i zustand # or yarn add zustand

 

2. store 생성

 

// store.js 타입스크립트이면 store.tsx

import { create } from "zustand" // create로 zustand를 불러 옴

 

const useStore = create(set => ({

    bears : 0,

    increasePopulation : () => set(state => ({ bears : state.bears + 1 })),

    removeAllBears : () => set({ bears : 0 })

}))

export default useStore

 

bears 라는 초기값을 선언. 이 값을 조작하는 increasePopulation( bears를 1씩 증가)과

removeAllBears( bears를 0으로 리셋) 함수. 이때는 set을 활용

 

3. store에 생성한 useStore를 불러와서 사용

 

//App.js 

import useStore from "../store.js"

 

const App = () => {

    const { bears, increasePopulation, removeAllBears } = useStore(state => state)

 

return (

     <>

          <h1>{ bears } 주위에 ... </h1>

          <button onClick={ increasePopulation }> one up </button>

           <button onClick={ removeAllBears  }> remove all </button>

      </>

  )

}

Devtools를 통해 상태 Debugging 하기

Zustand는 Middleware로 Devtools를 지원하고 있어서 쉽게 Redux DevTools를 Chrome 웹 스토어에서 설치

 

// store.js 타입스크립트이면 store.tsx

 

import { create } from "zustand"

import { devtools } from "zustand/middleware"

 

const useStore = 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를 불러온 후 연결 한 뒤, 브라우저에서 개발자 도구 창에서 Redux DevTools를 확인하면 store의 상태를 확인 할 수 있다.

반응형

댓글