본문 바로가기
코딩

Zustand 공부 시작

by KUROMI98 2025. 8. 4.

npm install zustand 해서 zustand 설치하고

 

import { create } from "zustand";

이렇게 create를 불러와 준다. create는 zustand에서 전역 상태를 만들기 위한 함수다. 이걸 호출해서 상태 저장을 할 수 있는 것이다.

 

const useAppStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

set함수는 zustand가 내부에서 제공하는 함수로, 상태를 업데이트할 때 사용한다. set((기존상태) => 새로운 상태) 로 사용한다.

count: 0은 초기 상태가 0이라는 거다.

increment는 action 함수로, 현재의 count 값을 받아서 +1로 업데이트 하는 식이다.

 

import useAppStore from "./store/useAppStore";
import "./App.css";

function App() {
  const count = useAppStore((state) => state.count);
  const increment = useAppStore((state) => state.increment);
  return (
    <div>
      <h1> hello zustand </h1>
      <p> {count} </p>
      <button onClick={() => increment()}>increment</button>
    </div>
  );
}

export default App;

열심히 증가 버튼을 눌러 보면 숫자가 늘어나는 것을 볼 수 있다.

댓글