본문 바로가기
코딩

Zustand를 사용한 Todo List 만들기

by KUROMI98 2025. 8. 5.

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;

상태 관리를 처음으로 배워보는 것인데 이제 사용법을 다 익힌 것 같다!

댓글