useObserver hook

  1. useObserver<T>(fn: () => T, baseComponentName = "observed", options?: IUseObserverOptions): T
  2. interface IUseObserverOptions {
  3. // optional custom hook that should make a component re-render (or not) upon changes
  4. useForceUpdate: () => () => void
  5. }

The hook is available only with mobx-react-lite library or mobx-react@6.

Low level implementation used internally by observer HOC and Observer component.

It allows you to use an observer like behaviour, but still allowing you to optimize the component in any way you want (e.g. using memo with a custom areEqual, using forwardRef, etc.) and to declare exactly the part that is observed (the render phase).

One good thing about this is that if any hook changes an observable for some reason then the component won't rerender twice unnecessarily. (example pending)

  1. import { useObserver, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  2. function Person() {
  3. const person = useLocalStore(() => ({ name: 'John' }))
  4. return useObserver(() => (
  5. <div>
  6. {person.name}
  7. <button onClick={() => (person.name = 'Mike')}>No! I am Mike</button>
  8. </div>
  9. ))
  10. }

Despite using useObserver hook in the middle of the component, it will re-render a whole component on change of the observable. If you want to micro-manage renders, feel free to use <Observer /> or useForceUpdate option (for advanced users).