빠른 참조

MobX 치트시트

MobX 핵심 참조 가이드: 반응형 상태 관리, observable 속성, computed 연산 값, actions, autorun 부수 효과 및 React 연동.

· 게시일

MobX는 투명한 함수형 반응형 프로그래밍(TFRP)을 적용하여 상태 관리를 간결하고 직관적으로 만들어 주는 라이브러리입니다.

상태 및 액션 정의 (최신 MobX 6+)

import { makeAutoObservable, observable, action, computed } from 'mobx';

class CartStore {
  items = [];

  constructor() {
    makeAutoObservable(this);
  }

  get totalCount() {
    return this.items.reduce((sum, item) => sum + item.quantity, 0);
  }

  addItem(product) {
    this.items.push(product);
  }

  removeItem(productId) {
    this.items = this.items.filter((item) => item.id !== productId);
  }
}

export const cartStore = new CartStore();

리액션 (Reactions)

컴포넌트를 observer로 감싸면 감시 중인 상태가 바뀔 때 자동으로 리렌더링됩니다:

autorun()

즉시 실행되고 접근된 observable을 추적하여 변경 시마다 자동으로 다시 실행됩니다:

import { autorun } from 'mobx';

const disposer = autorun(() => {
  console.log(`Cart total count: ${cartStore.totalCount}`);
});

// 감시 중지
disposer();

reaction()

데이터 추적과 부수 효과 실행을 명확히 분리하는 정밀한 리액션:

import { reaction } from 'mobx';

reaction(
  () => cartStore.items.length,
  (length, prevLength) => {
    console.log(`Cart item count changed from ${prevLength} to ${length}`);
  }
);

when()

조건 함수가 true를 반환할 때 단 한 번 부수 효과를 실행:

import { when } from 'mobx';

when(
  () => cartStore.totalCount > 10,
  () => console.log('Eligible for bulk discount!')
);

React 연동 (mobx-react-lite)

컴포넌트를 observer로 감싸면 감시 중인 상태가 바뀔 때 자동으로 리렌더링됩니다:

import React from 'react';
import { observer } from 'mobx-react-lite';
import { cartStore } from './CartStore';

export const CartSummary = observer(() => {
  return (
    <div>
      <h2>Total Items: {cartStore.totalCount}</h2>
      <button onClick={() => cartStore.addItem({ id: 1, quantity: 1 })}>
        Add Item
      </button>
    </div>
  );
});

관련 참고 자료

관련 주제