액션은 상태 변경에만 집중하자.
액션 내부에서 API를 호출한다거나, setTimeOut을 한다거나 복잡한 조건 분기를 하는 것은 피하자.
액션은 단순한 상태 변환에만 충실해야 한다. 그래야 스토어가 단순하고 이해하기 쉬워진다.
액션 하나로 여러 상태를 동시에 업데이트할 수 있다.
액션이 많아지면 그룹화하거나 슬라이스로 분리하는 것이 좋다.
상태 변경은 반드시 set으로!

import useAppStore from "./store/useAppStore";
import "./App.css";
function App() {
const count = useAppStore((state) => state.count);
const username = useAppStore((state) => state.username);
const increment = useAppStore((state) => state.increment);
const decrement = useAppStore((state) => state.decrement);
const resetUsername = useAppStore((state) => state.resetUsername);
const resetNumber = useAppStore((state) => state.resetNumber);
const setUsername = useAppStore((state) => state.setUsername);
return (
<div style={{ padding: "32px" }}>
<h1>Hello Zustand</h1>
<div>
<label>
이름:
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="이름을 입력하세요."
style={{ marginLeft: "8px" }}
/>
</label>
</div>
<p>어서 오세요, {username || "무명"}님!</p>
<button onClick={resetUsername} style={{ marginRight: "8px" }}>
이름 초기화
</button>
<div style={{ marginTop: "16px" }}>
<p>카운트: {count}</p>
<button onClick={increment} style={{ marginRight: "8px" }}>
+
</button>
<button onClick={decrement} style={{ marginRight: "8px" }}>
-
</button>
<button onClick={resetNumber}>번호 초기화</button>
</div>
</div>
);
}
export default App;
-
import { create } from "zustand";
const useAppStore = create((set) => ({
count: 0,
username: "",
setUsername: (name) => set({ username: name }),
resetUsername: () => set({ username: "" }),
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
resetNumber: () => set({ count: 0 }),
}));
export default useAppStore;
여기서
increment: () => set((count) => ({ count: count + 1 })), // ❌
decrement: () => set((count) => ({ count: count - 1 })), // ❌
이렇게 하면 안된다. 왜냐? state라는 거는 count, username, setUsername... 등의 객체인데,
state의 count를 변경하려는 것이기 때문에
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
이렇게 해야 한다.
'코딩' 카테고리의 다른 글
| jQuery를 사용하면 코드가 간단해진다. (0) | 2025.08.08 |
|---|---|
| Zustand를 사용한 Todo List 만들기 (0) | 2025.08.05 |
| Zustand 공부 시작 (0) | 2025.08.04 |
| HTML + JS + CSS 간단한 토글 Navigation Bar 만들기 (0) | 2025.07.29 |
| HTML + CSS + JS 알림 창 만들기 (0) | 2025.07.28 |
댓글