Introduction

MobX in React brings easy reactivity to your components. It can handle whole application state as well.

This site shows examples with React functional components and Hooks. Class components work in a similar way. In case there is class-specific behavior, we will mention it and supply an appropriate example.

Check out the example of the amazing Todo application or continue reading on why to observe or how to manage state.

Do you want to migrate toward Hooks? Have a look at our migration guide.

  1. import React from 'react'
  2. import { observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  3. export const TodoList = observer<{ initialTodos: string[] }>(
  4. ({ initialTodos }) => {
  5. const todoRef = React.useRef()
  6. const store = useLocalStore(() => ({
  7. todos: createTodos(initialTodos) as Record<string, boolean>,
  8. get pendingTodos() {
  9. return Object.keys(store.todos).filter(
  10. todo => store.todos[todo] === false,
  11. )
  12. },
  13. get doneTodos() {
  14. return Object.keys(store.todos).filter(
  15. todo => store.todos[todo] === true,
  16. )
  17. },
  18. addTodo: () => {
  19. store.todos[todoRef.current.value] = false
  20. todoRef.current.value = ''
  21. },
  22. toggleTodo: (todo: string) => {
  23. store.todos[todo] = !store.todos[todo]
  24. },
  25. }))
  26. const renderTodo = (done: boolean) => todo => (
  27. <Todo key={todo} done={done} text={todo} onToggle={store.toggleTodo} />
  28. )
  29. return (
  30. <form onSubmit={store.addTodo}>
  31. {store.pendingTodos.map(renderTodo(false))}
  32. {store.doneTodos.map(renderTodo(true))}
  33. <br />
  34. <input ref={todoRef} />
  35. <button>Add todo</button>
  36. </form>
  37. )
  38. },
  39. )