Skip to content

Commit 7ebc32a

Browse files
committed
[zustand] 상태 관리
1 parent f7093f8 commit 7ebc32a

File tree

1 file changed

+129
-1
lines changed

1 file changed

+129
-1
lines changed

zustand/overview.md

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Zustand 5.0.5
1+
# [Zustand 5.0.5](https://zustand.docs.pmnd.rs/getting-started/introduction)
22

33
- 작고 빠르며 확장 가능한 React 프로젝트에서 사용하는 상태 관리(Store) 라이브러리이다.
44

@@ -202,4 +202,132 @@ export default function App() {
202202
}
203203
```
204204

205+
## 상태 초기화
206+
207+
```ts
208+
const useSomeStore = create<State & Actions>()((set, get, store) => ({
209+
// your code here
210+
reset: () => {
211+
set(store.getInitialState());
212+
},
213+
}));
214+
```
215+
216+
- resetState : 상태와 액션을 분리해서 타입과 초깃값을 작성한다.
217+
218+
```ts
219+
import type { StateCreator } from 'zustand'
220+
import { create: actualCreate } from 'zustand'
221+
222+
const storeResetFns = new Set<() => void>()
223+
224+
const resetAllStores = () => {
225+
storeResetFns.forEach((resetFn) => {
226+
resetFn()
227+
})
228+
}
229+
230+
export const create = (<T>() => {
231+
return (stateCreator: StateCreator<T>) => {
232+
const store = actualCreate(stateCreator)
233+
storeResetFns.add(() => {
234+
store.setState(store.getInitialState(), true)
235+
})
236+
return store
237+
}
238+
}) as typeof actualCreate
239+
240+
```
241+
242+
## 상태 삭제
243+
244+
- set 함수의 두번째 인수로 true를 전달하면 상태를 병합하지 않고 덮어쓴다.
245+
- Lodash의 omit 함수 : 특정 속성들을 제외한 새로운 객체를 반환한다.
246+
이를 조합하면 특정 상태들을 삭제할 수 있다.
247+
248+
## 미들웨어
249+
250+
```ts
251+
// 미들웨어 없이
252+
create(콜백);
253+
254+
// 단일 미들웨어
255+
import { 미들웨어 } from "미들웨어";
256+
create(미들웨어(콜백));
257+
258+
// 다중 미들웨어
259+
import { 미들웨어A } from "미들웨어A";
260+
import { 미들웨어B } from "미들웨어B";
261+
import { 미들웨어C } from "미들웨어C";
262+
create(미들웨어A(미들웨어B(미들웨어C(콜백))));
263+
264+
// 타입을 사용하는 경우
265+
create(미들웨어A(미들웨어B(미들웨어C<타입>(콜백))));
266+
```
267+
268+
### 다중 미들 웨어
269+
270+
- 중첩 순서가 중요하다.
271+
272+
### 상태의 타입 추론
273+
274+
- combine 미들웨어 사용한다.
275+
- 첫번째 인수로 추론할 상태를 받고 두번째 인수로 set, get 매개변수를 포함하는 액션 함수를 받는다.
276+
- 추론 가능하지 않은 타입은 직접 작성한다.(satisfies, as 키워드 사용)
277+
278+
### 중첩된 객체 변경
279+
280+
[Immer](https://immerjs.github.io/immer/)\*라이브러리 를 설치 후 사용한다.
281+
282+
```ts
283+
immerInc: () =>
284+
set(produce((state: State) => { ++state.deep.nested.obj.count })),
285+
286+
```
287+
288+
```ts
289+
import { create } from "zustand";
290+
import { immer } from "zustand/middleware/immer";
291+
292+
type State = {
293+
count: number;
294+
};
295+
296+
type Actions = {
297+
increment: (qty: number) => void;
298+
decrement: (qty: number) => void;
299+
};
300+
301+
export const useCountStore = create<State & Actions>()(
302+
immer((set) => ({
303+
count: 0,
304+
increment: (qty: number) =>
305+
set((state) => {
306+
state.count += qty;
307+
}),
308+
decrement: (qty: number) =>
309+
set((state) => {
310+
state.count -= qty;
311+
}),
312+
}))
313+
);
314+
```
315+
316+
### 상태 구독
317+
318+
### 스토리지 사용(persist)
319+
320+
persist 미들웨어를 사용해 스토리지에 상태를 저장하고 불러올 수 있다.
321+
name을 제공해야 한다.
322+
localStorage 를 기본으로 사용하고 필요하면 sessionStorage나 customStorage 를 만들어서 사용할 수 있다.
323+
324+
```ts
325+
persist — ["zustand/persist", YourPersistedState]
326+
```
327+
328+
### 개발자 도구
329+
330+
- [Redux](https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?pli=1)랑 같이 사용하면 상태 모니터링이 가능하다.
331+
- devtools 미들웨어 사용시 개발자 도구 활성화된다.
332+
205333
[도움](https://www.heropy.dev/p/n74Tgc)

0 commit comments

Comments
 (0)