사내에서 새롭게 시작하는 프로젝트에서 새로운 상태관리 라이브러리를 써보자고 해서 조사하다가 도입하게된 "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의 상태를 확인 할 수 있다.
'Front-End > Next.js(React | Ts|Js)' 카테고리의 다른 글
자바스크립트(JS)Math 메서드 정리2(floor, round, ceil) (0) | 2023.07.31 |
---|---|
자바스크립트(JS)Math 메서드 정리1(abs, min, max) (0) | 2023.07.27 |
[Next.js] SSG(Static Site Generation)과 ISR 설명 및 사용법 -프론트엔드개발 (0) | 2023.07.11 |
[Next.js] 13 Image 태그 사용법 및 특징 -프론트엔드개발 (0) | 2023.06.20 |
자바스크립트(JS)문자열 자르기 함수(split, substr, substring, slice) (0) | 2023.06.13 |
댓글