Next.js & MobX 사용하기

조예진·2021년 10월 26일
0
post-thumbnail

이번 프로젝트에서는 MobX를 사용하려고 한다. 빠르게 완성되어야 하고 규모가 작은 프로젝트이기 때문이다.

Redux의 경우에는 스토어 하나를 만들기 위해서 작성해야 하는 코드가 너무 많고 복잡해서, 비교적 쉽고 간단한 MobX를 사용하기로 했다. 확실히 스토어를 만들고 사용하는 방식이 쉽고 간단하다.

1. 설치

npm install mobx mobx-react

2. 스토어 생성

// @src/store/count.store
import { makeAutoObservable } from "mobx";

class Count {
  number: number = 0;

  constructor() {
    makeAutoObservable(this);
  }

  increase = () => {
    this.number += 1;
  };

  decrease = () => {
    this.number -= 1;
  };
}

const countStore = new Count();
export default countStore;

3. 스토어 적용

import type { NextPage } from "next";
import { observer } from "mobx-react";
import countStore from "@src/store/count.store";

const Home: NextPage = observer(() => (
  <div>
    <p>{countStore.number}</p>
    <button onClick={countStore.increase} type="button">
      +
    </button>
    <button onClick={countStore.decrease} type="button">
      -
    </button>
  </div>
));

export default Home;

이 때, 컴포넌트를 observer() 로 감싸주어야 한다.

profile
https://oooooroblog.com 으로 이사갔어요

0개의 댓글