In the MobX with React docs, in the Side effects and observables section there is a receipe to respond to changes inside a useEffect
hook.
import React from 'react'
import { autorun } from 'mobx'
function useDocumentTitle(store: TStore) {
React.useEffect(
() =>
autorun(() => {
document.title = `${store.title} - ${store.sectionName}`
}),
[], // note empty dependencies
)
}
The example combines React.useEffect
with mobx.autorun
(but it could be mobx.reaction
), but I can not see the benefit of autorun
in the code. Once we are inside useEffect
we can track our dependencies in the dependency array. The code is more clear, there is no need to dispose()
and useEffect
has a clear dependency array with what is needed.
import React from 'react'
import { autorun } from 'mobx'
function useDocumentTitle(store: TStore) {
React.useEffect(() => document.title = `${store.title} - ${store.sectionName}`
,[store.title, store.sectionName])
}
Is there any reason to follow the example as given?
Here is a Code Sandbox
autorun
creates an observer, which means it will watch for any changes in store.title
and store.sectionName
, and automatically run whenever they change.
Setting it up in useEffect
ensures that the autorun
observer is only created once, and removed when the component is unmounted.
Your second example without autorun
might still update the title if there's an observer in a parent component that triggers a re-render (of itself and its children, including this component). However, if you don't observe the store.title
and store.sectionName
in a parent component, you'll need to observe it in this component, and autorun
is a good way to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With