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.
observer<P>(baseComponent: React.FC<P>, options?: IObserverOptions): React.FC<P>
interface IObserverOptions {
// Pass true to use React.forwardRef over the inner component. It's false by the default.
forwardRef?: boolean
}
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 underlyingReact.memo
will effectively prevent that update to propagate.Try to avoid using legacy context or alternatively use
Observer
component oruseObserver
hook.
import { observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
export const Counter = observer<Props>(props => {
const store = useLocalStore(() => ({
count: props.initialCount,
inc() {
store.count += 1
},
}))
return (
<div>
<span>{store.count}</span>
<button onClick={store.inc}>Increment</button>
</div>
)
})