Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using react.useEffect and mobx.autorun together

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

like image 306
David Casillas Avatar asked Oct 09 '19 14:10

David Casillas


1 Answers

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.

like image 80
Petr Bela Avatar answered Oct 19 '22 07:10

Petr Bela