Next.js & MobX 사용하기

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

2021-10-26에 씀

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

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

1. 설치

npm install mobx mobx-react

2. 스토어 생성

1// @src/store/count.store
2import { makeAutoObservable } from "mobx";
3
4class Count {
5 number: number = 0;
6
7 constructor() {
8 makeAutoObservable(this);
9 }
10
11 increase = () => {
12 this.number += 1;
13 };
14
15 decrease = () => {
16 this.number -= 1;
17 };
18}
19
20const countStore = new Count();
21export default countStore;

3. 스토어 적용

1import type { NextPage } from "next";
2import { observer } from "mobx-react";
3import countStore from "@src/store/count.store";
4
5const 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));
16
17export default Home;

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

프로필 사진

조예진

이전 포스트
TypeScript 프로젝트에서 Absolute Path 사용시 [import/no-unresolved] 에러
다음 포스트
getServerSideProps를 사용하는 Next.js 프로젝트를 Netlify에 배포하기