[React]MobX 적용

Philip Sung·2023년 4월 27일
0

[React]

목록 보기
2/2
post-thumbnail

01 개요

리액트 2023년 현재 사용되고 있는 상태 관리 라이브러리(state management library) MobX를 사용해서 어플리케이션의 상태관리를 하기 위한 전반적인 내용을 다룬다.

최종수정일 : 2023.04.27



02 환경설정

npm install mobx --save
npm install mobx-react-lite --save




03 주요 개념

03.01 개념

State : 객체, 배열, 원시 값, 참조 등 데이터
Action : state를 변경하는 모든 동작
Derivation : state로부터 추론될 수 있는 모든 데이터
Reaction : state의 변경에 수반되는 동작

03.02 사용

observable : 특정 객체를 MobX가 값을 추적하고 변경할 수 있는 객체로 만든다.
computed : 특정 데이터 객체를 MobX가 연동된 값에 의해 계산해 재조정 할 수 있도록 만든다.




04 예제

출처는 [10분만에 알아보는 MobX와 React] : https://ko.mobx.js.org/getting-started.html 이다.

04.01 store 생성


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();

04.02 React 코드 작성(Front-End)

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')
);

04.03 참조(Reference) 작업

const peopleStore = observable([
 { name: "Michel" },
 { name: "Me" }
]);
observableTodoStore.todos[0].assignee = peopleStore[0];
observableTodoStore.todos[1].assignee = peopleStore[1];
peopleStore[0].name = "Michel Weststrate";




99 참조링크

https://ko.mobx.js.org/the-gist-of-mobx.html
https://ko.mobx.js.org/getting-started.html
https://juzero-space.tistory.com/270

profile
Philip Sung

0개의 댓글