Zustand โ
Reference
๐ Zustand Docs
Zustand ์๊ฐ โ
Zustand๋? โ
- ๋ ์ผ์ด๋ก ์ํ๋ผ๋ ์๋ฏธ
- 2019๋ , Poimandres ํ์์ ๊ฐ๋ฐ
- React์ Hooks์ ์์ฐ์ค๋ฝ๊ฒ ํตํฉ๋๋ ๊ฒฝ๋ ์ํ ๊ด๋ฆฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
๊ธฐ๋ณธ ์ฌ์ฉ ์์ โ
jsx
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}));
function Counter() {
const { count, increment } = useStore();
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>+1</button>
</div>
);
}createํจ์๋ก ์ํ์ ์ ๋ฐ์ดํธ ํจ์๋ฅผ ์ ์- ์ปดํฌ๋ํธ์์๋
useStoreํ ์ ํธ์ถํด ๋ฐ๋ก ์ฌ์ฉ ๊ฐ๋ฅ - ์ํ์ ๋ก์ง์ด ํ ๊ณณ์ ๋ชจ์ฌ ๊ด๋ฆฌ๊ฐ ๋จ์ํด์ง๋ค.
Zustand ์ฅ์ โ
- ๊ฐ๊ฒฐํจ: ๋ณด์ผ๋ฌํ๋ ์ดํธ ์ฝ๋๊ฐ ๊ฑฐ์ ์์
- ๋ฎ์ ๋ฌ๋์ปค๋ธ: ํ ๊ธฐ๋ฐ API๋ผ ์ฝ๊ฒ ํ์ต ๊ฐ๋ฅ
- ์ ์ฐํ ๊ตฌ์กฐ: ์์ ํ๋ก์ ํธ๋ถํฐ ํฐ ํ๋ก์ ํธ๊น์ง ์ ์ฉ ๊ฐ๋ฅ
- Provider ๋ถํ์: Context Provider ์์ด ์ ์ญ ์ํ ์ฌ์ฉ ๊ฐ๋ฅ
jsx
function DeepComponent() {
const count = useStore((state) => state.count);
return <div>{count}</div>;
}- ๋ฆฌ๋ ๋๋ง ์ต์ ํ: ํ์ํ ์ํ๋ง ์ ํ์ ์ผ๋ก ๊ตฌ๋ ๊ฐ๋ฅ
jsx
const count = useStore((state) => state.count);
const increment = useStore((state) => state.increment);
// count๊ฐ ๋ณํด๋ increment๋ ๋ค์ ๋ ๋๋ง๋์ง ์์- TypeScript ์ง์ - ํ์ํ ์ํ๋ง ์ ํ์ ์ผ๋ก ๊ตฌ๋ ๊ฐ๋ฅ
๋ค๋ฅธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ๋น๊ต โ
| ๋ผ์ด๋ธ๋ฌ๋ฆฌ | ํน์ง | ๋ณต์ก๋ | ๋ฌ๋์ปค๋ธ |
|---|---|---|---|
| Redux | ๋ณด์ผ๋ฌํ๋ ์ดํธ ๋ง์ | ๋์ | ๋์ |
| Context API | ๋ด์ฅ ๊ธฐ๋ฅ, ์ฑ๋ฅ ์ด์ ์์ | ์ค๊ฐ | ์ค๊ฐ |
| Jotai / Recoil | ์์ ๊ธฐ๋ฐ ์ํ, ์์กด์ฑ ํํ | ์ค๊ฐ | ์ค๊ฐ |
| Zustand | ๊ฐ๊ฒฐํ๊ณ ์ง๊ด์ , ์ฑ๋ฅ ์ต์ ํ | ๋ฎ์ | ๋ฎ์ |
์ Zustand๋ฅผ ๋ฐฐ์์ผ ํ ๊น? โ
- ๋ณต์กํ ์ํ ๊ด๋ฆฌ ๋ฌธ์ ๋ฅผ ๊ฐ๊ฒฐํ๊ณ ์ง๊ด์ ์ผ๋ก ํด๊ฒฐ
- React ํ๋ก์ ํธ์ ๋ฐ๋ก ์ ์ฉ ๊ฐ๋ฅ
- ๋ฌ๋ ์ปค๋ธ๊ฐ ๋ฎ์ ํ์ต ํจ์จ์ด ๋์
Redux vs Zustand โ
- Redux: ์ก์ , ๋ฆฌ๋์, ๋ฏธ๋ค์จ์ด ๋ฑ ๊ตฌ์กฐ๊ฐ ๋ฌด๊ฒ๊ณ ๋ณต์ก
- Zustand: ๋จ์ผ ์คํ ์ด, ํ
๊ธฐ๋ฐ, ์ง๊ด์ ์ธ API โ ํ ์ค๋ก ์ํ์ ์
๋ฐ์ดํธ ๋ก์ง์ ์ ์ํ ์ ์์jsx
// Zustand๋ ํ ์ค๋ก ์ํ + ํจ์ ๊ตฌ์ฑ create (() => ({ count: 0, inc: () => {...} }))