useObserver hook
useObserver<T>(fn: () => T, baseComponentName = "observed", options?: IUseObserverOptions): T
interface IUseObserverOptions {
// optional custom hook that should make a component re-render (or not) upon changes
useForceUpdate: () => () => void
}
The hook is available only with
mobx-react-lite
library ormobx-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)
import { useObserver, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
function Person() {
const person = useLocalStore(() => ({ name: 'John' }))
return useObserver(() => (
<div>
{person.name}
<button onClick={() => (person.name = 'Mike')}>No! I am Mike</button>
</div>
))
}
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).