Adding reactivity to React components

There are three ways to add reactivity to components:

😎 observer HOC

🤓 observer component

🧐 useObserver hook

In most cases, their difference doesn't matter that much, but here is an overview of the three different approaches

  1. import { observable } from 'mobx'
  2. import { Observer, useObserver, observer } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  3. import ReactDOM from 'react-dom'
  4. const person = observable({
  5. name: 'John',
  6. })
  7. // named function is optional (for debugging purposes)
  8. const P1 = observer(function P1({ person }) {
  9. return <h1>{person.name}</h1>
  10. })
  11. const P2 = ({ person }) => <Observer>{() => <h1>{person.name}</h1>}</Observer>
  12. const P3 = ({ person }) => {
  13. return useObserver(() => <h1>{person.name}</h1>)
  14. }
  15. ReactDOM.render(
  16. <div>
  17. <P1 person={person} />
  18. <P2 person={person} />
  19. <P3 person={person} />
  20. </div>,
  21. )
  22. setTimeout(() => {
  23. person.name = 'Jane'
  24. }, 1000)

Edit MobX in React - observer pattern

Curious what makes observability so great and why you should do it?