일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- SOLID
- frontend
- react
- DM
- mongo
- PyTorch
- postgresql
- figma
- html
- CSS
- CV
- vscode
- Linux
- ML
- nodejs
- js
- C++
- API
- sqlite
- Git
- threejs
- PRISMA
- GAN
- ts
- DB
- Express
- python
- ps
- UI
- review
- Today
- Total
아카이브
[Frontend] Zustand에 대해서 본문
Zustand는 프레임워크 독립적인 상태관리 라이브러리중 하나입니다.
Store라는 개념을 이용하여 불필요한 props전달을 최소화합니다.
다음과 같이 설치합니다.
npm install zustand
※ Zustand는 현재 프레임워크 독립 라이브러리이나, 처음에는 React 전용 라이브러리로 개발되었습니다. 따라서 아래는 React를 기준으로 서술하였습니다.
create( )
Store를 생성하는 함수입니다.
속성값과 메소드를 포함한 객체를 반환하며, Store 안에서 속성값은 State, 메소드는 Action이라고 표현합니다.
기본적으로 set과 get 두 가지 매개변수를 받습니다.
get 함수는 자기 자신 Store 객체를 반환합니다.
set 함수는 Store의 값을 설정할 수 있습니다. 만약 인수로 콜백함수를 사용한다면, get( ) 사용 없이 바로 자기 자신 객체를 사용할 수 있습니다.
이름의 경우, 관습적으로 use~Store의 형식으로 짓는다고 합니다.
import { create } from 'zustand'
export const accountStore = create((set, get) => {
return {
name: "Jhon", // state
age: 18, // state
initAge: set({age: 20}), // action
decreaseAge: () => { // action
const { age } = get();
set({ age: age - 1 })
}
increaseAge: set((state) => ({ age: state.age + 1 })), // action
}
})
사용하기
다음과 같이 사용하고자 하는 state 혹은 action을 호출하는 형태의 콜백과 함께 사용합니다.
이 경우 콜백으로 호출한 값이 변경될 때만 컴포넌트가 다시 랜더링됩니다.
import { useStore } from './store/bear-store.js';
BearCounter = () => {
const bears = useStore((state) => state.bears);
return <h1>곰이 {bears}마리 있습니다.</h1>
}
Controls = () => {
const increasePopulation = useStore((state) => state.increasePopulation);
return <button onClick={increasePopulation}>한마리 추가</button>
}
Store에서 불러와야 하는 값들이 많다면, 아예 store 전체를 불러오는 것도 가능합니다.
const useSys = useStore(state => state);
하지만 이 경우, 모든 상태값에 대해 컴포넌트가 다시 랜더링되기 때문에 성능 저하가 발생할 수 있어 권장하지는 않습니다.
https://zustand.docs.pmnd.rs/getting-started/introduction
Introduction - Zustand
How to use Zustand
zustand.docs.pmnd.rs
※ TypeScript에서의 제네릭 사용은 다음과 같이 합니다.
import { create } from 'zustand'
export const accountStore = create<{
name: string,
age: number,
initAge: () => void,
decreaseAge: () => void,
increaseAge: () => void,
}>((set, get) => {
return {
// ...
}
})
'Frontend' 카테고리의 다른 글
[Fronted] 상태관리 라이브러리 (0) | 2025.04.14 |
---|---|
[Three] Three.js 프로젝트 시작하기 (0) | 2025.01.12 |
[Three] Three.js에 대해서 (0) | 2025.01.12 |
[TS] Could not find a declaration file for module '...' 해결하기 (0) | 2024.12.19 |
[Frontend] 효율적인 비동기 코드 (0) | 2024.07.26 |