Observer component
- <Observer>{renderFn}</Observer>
Works the same way with
mobx-react
ormobx-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.
import { Observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
export function ObservePerson() {
const person = useLocalStore(() => ({ name: 'John' }))
return (
<div>
{person.name} <i>I will never change my name</i>
<div>
<Observer>{() => <div>{person.name}</div>}</Observer>
<button onClick={() => (person.name = 'Mike')}>
I want to be Mike
</button>
</div>
</div>
)
}
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.
import { Observer } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
function ObservePerson() {
return (
<Observer>
{() => (
<GetStore>{store => <div>{store.wontSeeChangesToThis}</div>}</GetStore>
)}
</Observer>
)
}
You need to switch it around to work around the problem. Or use React Hooks if possible.
import { Observer } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0
function ObservePerson() {
return (
<GetStore>
{store => (
<Observer>{() => <div>{store.changesAreSeenAgain}</div>}</Observer>
)}
</GetStore>
)
}