Zustand를 사용해보자
date
Sep 9, 2022
thumbnail
slug
Zustand를 사용해보자
author
status
Published
tags
Library
React
summary
1. 서론
React에서의 상태관리는 총 2가지로 분류할 수 있어요.서버 상태관리, 로컬 상태관리인데요.
서버 상태관리 라이브러리는 대표적으로
SWR
, React-Query
가 있고 로컬 상태관리는 대표적으로 Recoil
, Zustand
, Jotai
, Redux
같은 툴이 있어요.
로컬 상태관리 툴은 2가지로 분류할 수 있는데 FLUX 구조
, Atomic 구조
로 나눌 수 있어요.
오늘은 Flux 구조
를 사용하는 Zustand
를 사용해보려고 해요.type
Post
updatedAt
Jan 22, 2023 01:19 AM
1. 서론
React에서의 상태관리는 총 2가지로 분류할 수 있어요.서버 상태관리, 로컬 상태관리인데요.
서버 상태관리 라이브러리는 대표적으로
SWR
, React-Query
가 있고 로컬 상태관리는 대표적으로 Recoil
, Zustand
, Jotai
, Redux
같은 툴이 있어요.로컬 상태관리 툴은 2가지로 분류할 수 있는데
FLUX 구조
, Atomic 구조
로 나눌 수 있어요.오늘은
Flux 구조
를 사용하는 Zustand
를 사용해보려고 해요.2. 본론
Zustand는 Jotai 및 React springs 개발자가 만든 상태관리 라이브러리에요.
“Zustand” is just German for “state”.
Zustand를 사용하는 이유는 다음과 같아요.
- 보일러플레이트 코드가 적다.
- Zustand는 상태 값 변경에만 요소를 렌더링해요. 다른 요소를 렌더링 하지 않아도 처리할 수 있어요.
- Flux 구조를 사용하고 있지만 Redux와 같은 복잡한 구조를 가지고 있지 않아요.
- hook을 사용해서 상태를 관리할 수 있어요.
- Provider를 사용하지 않아도 돼요.
Zustand 공식 홈페이지를 살펴볼까요?
![notion image](https://www.notion.so/image/https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FE5zyL%2FbtrLLzhFKwH%2FgaBoNyE6kLDmcALYzAKYrK%2Fimg.png?table=block&id=fced95f7-b192-4cac-93aa-86bef4658f75&cache=v2)
공식 문서가 없는데요..? 사이트에는 예제가 전부이고 자세한 것은 Github에 정리되어있어요.
2.1. 설치
npm install zustand
yarn add zustand
2.2. 사용법
먼저 store를 생성해봅시다.
import create from 'zustand';
// define the storeconst useStore = create(set => ({
votes: 0,
}));
votes라는 상태를 만들었어요. 이제 이 상태를 사용해볼까요?
const getVotes = useStore(state => state.votes);
return (
<div className="App">
<h1>You get {getVotes} Votes</h1>
</div>
);
이렇게 사용할 수 있어요.
2.3. 상태 변경
const useStore = create(set => ({
votes: 0,
increment: () => set(state => ({ votes: state.votes + 1 })),
decrement: () => set(state => ({ votes: state.votes - 1 })),
}));
increment
, decrement
라는 함수를 만들었어요. 이제 이 함수를 사용해봅시다.const addVotes = useStore(state => state.increment);
const subtractVotes = useStore(state => state.decrement);
<div className="App">
<h1>You get {getVotes} Votes</h1>
<button onClick={addVotes}>vote</button>
<button onClick={subtractVotes}>Delete a vote</button>
</div>
2.4. 상태에 접근하기
const useStore = create((set, get) => ({
votes: 0,
//...getVotes: () => get().votes,
}));
다른 곳에 저장된 값을 상태에 추가한다고 했을 때
get()
을 사용해서 값을 가져올 수 있어요.이 방법으로 여러 상태에 동일한 값을 추가할 수 있어요.2.5. 비동기 처리하기
const useStore = create((set) => ({
votes: {},
fetch: async (voting) => {
const response = await fetch(voting)
set({ votes: await response.json() })
},
}))
function App() {
const votes = useStore(state => state.Votes)
const fetch = useStore(state => state.fetch)
return (
<div className="App">
<h1>{votes.length} people have cast their votes</h1>
<button onClick={()=>{fetch(voting)}}>Fetch</button>
</div>
);
}
2.6. Persist State / Devtools
import create from 'zustand';
import {devtools, persist} from "zustand/middleware"
// and modify our existing stateconst store = create(devtools((set) => ({
fruits: ["apple", "banana", "orange"],
addFruits: (fruit) => {
set((state) => ({
fruits: [...state.fruits, fruit],
}));
},
})));
// persist the created state
store = persist(store, {name: "basket"})
// create the storeconst useStore = create(store);
위와 같은 방법으로 persist, devtools를 사용할 수 있어요.
개인적으로 Redux는 너무 복잡하고 불편해서 사용하지 않고 있는데 이렇게 개발자 경험을 높혀주는 툴이 있다는 것에 너무 감사하고 있어요. Redux가 너무 어렵고 이해하기 힘들다면 Zustand는 어떠신가요?