Observer component

  1. <Observer>{renderFn}</Observer>

Works the same way with mobx-react or mobx-react-lite library. No exceptions for class components.

Is a React component, which applies observer to an anonymous region in your component.

It takes as children a single, argumentless function which should return exactly one React component.

The rendering in the function will be tracked and automatically re-rendered when needed.

This can come in handy when needing to pass render function to external components (for example the React Native listview), or if you want to observe only relevant parts of the output for a performance reasons.

  1. import { Observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  2. export function ObservePerson() {
  3. const person = useLocalStore(() => ({ name: 'John' }))
  4. return (
  5. <div>
  6. {person.name} <i>I will never change my name</i>
  7. <div>
  8. <Observer>{() => <div>{person.name}</div>}</Observer>
  9. <button onClick={() => (person.name = 'Mike')}>
  10. I want to be Mike
  11. </button>
  12. </div>
  13. </div>
  14. )
  15. }

Nesting caveat

Observer can see observables only within its own render function. If you use another render prop component, it won't be able to observe changes. Consider following example.

  1. import { Observer } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  2. function ObservePerson() {
  3. return (
  4. <Observer>
  5. {() => (
  6. <GetStore>{store => <div>{store.wontSeeChangesToThis}</div>}</GetStore>
  7. )}
  8. </Observer>
  9. )
  10. }

You need to switch it around to work around the problem. Or use React Hooks if possible.

  1. import { Observer } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  2. function ObservePerson() {
  3. return (
  4. <GetStore>
  5. {store => (
  6. <Observer>{() => <div>{store.changesAreSeenAgain}</div>}</Observer>
  7. )}
  8. </GetStore>
  9. )
  10. }