observer HOC

Is the most prominent from family of tools to introduce reactivity to your components. Please refer to React docs for a basic understanding of HOC pattern.

  1. observer<P>(baseComponent: React.FC<P>, options?: IObserverOptions): React.FC<P>
  2. interface IObserverOptions {
  3. // Pass true to use React.forwardRef over the inner component. It's false by the default.
  4. forwardRef?: boolean
  5. }

Use mobx-react if you need to observe class component. It doesn't support any of mentioned options, though.

The observer converts a component into a reactive component, which tracks which observables are used automatically and re-renders the component when one of these values changes.

Along the observer capability, the React.memo is applied to the component. The general idea is, that observed components rarely need to re-render based on a complex props.

⚠ WARNING

If component wrapped to observer depends on updates of legacy context, the underlying React.memo will effectively prevent that update to propagate.

Try to avoid using legacy context or alternatively use Observer component or useObserver hook.

  1. import { observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
  2. export const Counter = observer<Props>(props => {
  3. const store = useLocalStore(() => ({
  4. count: props.initialCount,
  5. inc() {
  6. store.count += 1
  7. },
  8. }))
  9. return (
  10. <div>
  11. <span>{store.count}</span>
  12. <button onClick={store.inc}>Increment</button>
  13. </div>
  14. )
  15. })