리액트 2023년 현재 사용되고 있는 상태 관리 라이브러리(state management library) MobX를 사용해서 어플리케이션의 상태관리를 하기 위한 전반적인 내용을 다룬다.
최종수정일 : 2023.04.27
npm install mobx --save
npm install mobx-react-lite --save
State : 객체, 배열, 원시 값, 참조 등 데이터
Action : state를 변경하는 모든 동작
Derivation : state로부터 추론될 수 있는 모든 데이터
Reaction : state의 변경에 수반되는 동작
observable : 특정 객체를 MobX가 값을 추적하고 변경할 수 있는 객체로 만든다.
computed : 특정 데이터 객체를 MobX가 연동된 값에 의해 계산해 재조정 할 수 있도록 만든다.
출처는 [10분만에 알아보는 MobX와 React] : https://ko.mobx.js.org/getting-started.html 이다.
class ObservableTodoStore { todos = []; pendingRequests = 0; constructor() { makeObservable(this, { todos: observable, pendingRequests: observable, completedTodosCount: computed, report: computed, addTodo: action, }); autorun(() => console.log(this.report)); } get completedTodosCount() { return this.todos.filter( todo => todo.completed === true ).length; } get report() { if (this.todos.length === 0) return "<none\>"; const nextTodo = this.todos.find(todo => todo.completed === false); return `Next todo: "${nextTodo ? nextTodo.task : "<none>"}". ` + `Progress: ${this.completedTodosCount}/${this.todos.length}`; } addTodo(task) { this.todos.push({ task: task, completed: false, assignee: null }); } } const observableTodoStore = new ObservableTodoStore();
const TodoList = observer(({store}) => { const onNewTodo = () => { store.addTodo(prompt('Enter a new todo:','coffee plz')); } return ( <div> { store.report } <ul> { store.todos.map( (todo, idx) => <TodoView todo={ todo } key={ idx } /> ) } </ul> { store.pendingRequests > 0 ? <marquee>Loading...</marquee> : null } <button onClick={ onNewTodo }>New Todo</button> <small> (double-click a todo to edit)</small> <RenderCounter /> </div> ); }) const TodoView = observer(({todo}) => { const onToggleCompleted = () => { todo.completed = !todo.completed; } const onRename = () => { todo.task = prompt('Task name', todo.task) || todo.task; } return ( <li onDoubleClick={ onRename }> <input type='checkbox' checked={ todo.completed } onChange={ onToggleCompleted } /> { todo.task } { todo.assignee ? <small>{ todo.assignee.name }</small> : null } <RenderCounter /> </li> ); }) ReactDOM.render( <TodoList store={ observableTodoStore } />, document.getElementById('reactjs-app') );
const peopleStore = observable([ { name: "Michel" }, { name: "Me" } ]); observableTodoStore.todos[0].assignee = peopleStore[0]; observableTodoStore.todos[1].assignee = peopleStore[1]; peopleStore[0].name = "Michel Weststrate";
https://ko.mobx.js.org/the-gist-of-mobx.html
https://ko.mobx.js.org/getting-started.html
https://juzero-space.tistory.com/270