Observable State (관찰 받고 있는 상태)
MobX를 사용하고 있는 앱의 상태는 Observable(관찰받고 있는 상태)이다. 앱에서 사용하고 있는 상태는 변할 수 있으며, 만약에 특정 부분이 바뀌면 MobX에서는 어떤 부분이 바뀌었는지 정확히 알 수 있다.
Computed Value (연산된 값)
기존의 상태값과 다른 연산된 값에 기반하여 만들어질 수 있는 값을 말한다. 이는 주로 성능 최적화를 위하여 많이 사용된다.
Reaction (반응)
Computed Value 와 비슷하다. Computed Value 의 경우는 우리가 특정 값을 연산해야 될 때 에만 처리가 되는 반면에, Reactions 은, 값이 바뀜에 따라 해야 할 일을 정하는 것을 의미
Actions (액션 : 행동)
상태에 변화를 일으키는 액션을 의미. 리덕스에서의 액션과 달리 따로 객체 형태로 만들지 않는다.
observable
: Observable State 만들기import { observable, reaction, computed, autorun } from 'mobx'; // **** Observable State 만들기 const calculator = observable({ a: 1, b: 2 });
<실습>
- MobX 설치하기
npm i --save -d customize-cra --save -d react-app-rewired --save -d @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties --save -d core-decorators
- package.json의 scripts를 수정
... "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject", ... } ...
- package.json에 babel 세팅을 추가
... "babel": { "presets": [ "react-app" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], [ "@babel/plugin-proposal-class-properties", { "loose": true } ] ] } ...
- 프로젝트 파일 루트 폴더에 config-overrides.js를 추가
const { addDecoratorsLegacy, disableEsLint, // eslint를 끄는 것이 아니에요 ^^ override, } = require("customize-cra"); module.exports = { webpack: override( disableEsLint(), addDecoratorsLegacy() ), };
- tsconfig.json (혹은 jsconfig.json)에서 컴파일 옵션을 추가
{ "compilerOptions": { ... "experimentalDecorators": true ... }, ... }
npm i --save mobx --save mobx-react
최상단 컴포넌트 (index.tsx) 에서 Provider 를 설정
하위 컴포넌트에서 props 에 inject 시켜주기.
mobx에서 필요한 함수 불러오기.
import { observable, reaction, computed, autorun } from 'mobx';