
import useTodoStore from "./store/useAppStore";
function App() {
const input = useTodoStore((state) => state.input);
const setInput = useTodoStore((state) => state.setInput);
const todos = useTodoStore((state) => state.todos);
const addTodo = useTodoStore((state) => state.addTodo);
const removeTodo = useTodoStore((state) => state.removeTodo);
const clearTodos = useTodoStore((state) => state.clearTodos);
const handleAdd = () => {
if (input === "") {
return;
} else {
addTodo(input);
setInput("");
}
};
return (
<div style={{ padding: "32px" }}>
<h1>📝 Zustand Todo List</h1>
<div style={{ marginBottom: "16px" }}>
<input
type="text"
placeholder="할 일 입력"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleAdd();
}}
/>
<button onClick={handleAdd} style={{ marginLeft: "8px" }}>
추가
</button>
<button onClick={clearTodos} style={{ marginLeft: "8px" }}>
전체 삭제
</button>
</div>
<div>
{todos.map((todo, index) => (
<div key={todo.id} style={{ margin: "8px 0px" }}>
{index + 1}. {todo.text}
<button
onClick={() => removeTodo(todo.id)}
style={{ marginLeft: "8px" }}
>
삭제
</button>
</div>
))}
</div>
</div>
);
}
export default App;
-
import { create } from "zustand";
const useTodoStore = create((set) => ({
input: "",
todos: [],
setInput: (inputText) => set({ input: inputText }),
addTodo: (text) =>
set((state) => ({
todos: [...state.todos, { id: Date.now(), text }],
})),
removeTodo: (id) =>
set((state) => ({
todos: state.todos.filter((todo) => todo.id !== id),
})),
clearTodos: () => set({ todos: [] }),
}));
export default useTodoStore;
상태 관리를 처음으로 배워보는 것인데 이제 사용법을 다 익힌 것 같다!
'코딩' 카테고리의 다른 글
| jQuery를 사용하면 코드가 간단해진다. (0) | 2025.08.08 |
|---|---|
| Zustand 사용 원칙과 예제 (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 |
댓글