본문 바로가기
반응형

Library & Framework/Zustand5

[Zustand] 상태 값 초기화 하기 "react": "^18.2.0", "zustand": "^4.5.2" "typescript": "^5.2.2" How to reset state zustand에서는 상태값을 초기화시켜주는 내장 함수를 제공해주고 있을까? 찾아보니 따로 제공해주고 있는게 없어 별도로 정의해 사용해야만 한다. 그래도 공식문서에서 이러한 방식들이 있다고 안내해주고 있어 참고하여 만들어두면 좋다. 공식문서의 코드를 그대로 가져와보자. import { create } from 'zustand' // define types for state values and actions separately type State = { salmon: number tuna: number } type Actions = { addSalmon: (qty.. 2024. 4. 4.
[Zustand] get()을 사용하여 최신값 가져오기 "react": "^18.2.0", "zustand": "^4.5.2" "typescript": "^5.2.2" get은 도대체 언제 쓰는 걸까? 얼핏 zustand를 살펴보면 set/get을 제공해주고 있는데 get이라는 녀석을 언제 쓰라고 제공해 주는 건지 의아하다. Read from state in actions 혹시나 공식문서에 나와있나 살펴보면 Read from state in actions라는 세션으로 설명을 해주고 있다. const useSoundStore = create((set, get) => ({ sound: 'grunt', action: () => { const sound = get().sound ... 이러한 사용 방식은 store의 action 함수를 선언할 때 현재 store s.. 2024. 4. 3.
[Zustand] Auto Generating Selectors 설정으로 더 간단하게 state값 가져오기 "react": "^18.2.0", "zustand": "^4.5.2" "typescript": "^5.2.2", Auto Generating Selectors 공식문서에서 제공하는 선택기 자동 생성 패턴이다. const count = useCountStore((state) => state.count) 보통 이런 식으로 state값을 가져오기는 하는데 state => state.count 이런 방식조차 너무 자주쓰면 귀찮긴 하다. 훌륭하게도 zustand쪽에서 자동으로 실렉터를 생성해 주는 방식을 제공해 주어 그대로 적용해 보자. store/index.ts import { StoreApi, UseBoundStore } from 'zustand' type WithSelectors = S extends { .. 2024. 4. 3.
[Zustand] 스토어 값 한 번에 여러개 가져오기 (ft. useShallow) "react": "^18.2.0", "zustand": "^4.5.2" "typescript": "^5.2.2", 스토어 값 여러 개가 필요한 경우 이전 게시글 "[Zustand] Zustand 상태 관리 라이브러리 설치 및 기본 사용법"에서 스토어 값을 가져올 때 이런 식으로 사용했었다. import { useCountStore } from '../store/countStore' const CountButton = () => { const increase = useCountStore((state) => state.increase) const decrease = useCountStore((state) => state.decrease) return ( 증가 감소 ) } 하지만 한 컴포넌트에서 하나의 스토어.. 2024. 4. 3.
[Zustand] Zustand 상태 관리 라이브러리 설치 및 기본 사용법 "react": "^18.2.0", "zustand": "^4.5.2" "typescript": "^5.2.2", Zustand란? zustand는 수많은 상태 관리 라이브러리 중 하나로, 작은 패키지 크기와 직관적이며, 단순한 방식의 사용법을 제공하여 최근에 굉장히 각광받는 라이브러리이다. 개인적으로는 러닝커브가 높지 않다는 게 아주 큰 장점이 아닐까 싶다. Zustand 설치 및 적용 Zustand 설치 # NPM npm install zustand # Yarn yarn add zustand 여느 라이브러리와 같이 동일하게 추가를 해주고 별다른 설정은 필요 없다. Zustand 사용 아주 간단하게 설치를 마쳤으니 사용도 아주 손쉽게 해 보도록 하자. 공식문서에서도 아주 간단하게 설명이 되어있는데, 공.. 2024. 4. 1.
반응형
TOP