이번 프로젝트에서는 MobX를 사용하려고 한다. 빠르게 완성되어야 하고 규모가 작은 프로젝트이기 때문이다.
Redux의 경우에는 스토어 하나를 만들기 위해서 작성해야 하는 코드가 너무 많고 복잡해서, 비교적 쉽고 간단한 MobX를 사용하기로 했다. 확실히 스토어를 만들고 사용하는 방식이 쉽고 간단하다.
1. 설치
npm install mobx mobx-react
2. 스토어 생성
1// @src/store/count.store2import { makeAutoObservable } from "mobx";34class Count {5 number: number = 0;67 constructor() {8 makeAutoObservable(this);9 }1011 increase = () => {12 this.number += 1;13 };1415 decrease = () => {16 this.number -= 1;17 };18}1920const countStore = new Count();21export default countStore;
3. 스토어 적용
1import type { NextPage } from "next";2import { observer } from "mobx-react";3import countStore from "@src/store/count.store";45const Home: NextPage = observer(() => (6 <div>7 <p>{countStore.number}</p>8 <button onClick={countStore.increase} type="button">9 +10 </button>11 <button onClick={countStore.decrease} type="button">12 -13 </button>14 </div>15));1617export default Home;
이 때, 컴포넌트를 observer()
로 감싸주어야 한다.