Search code examples
reactjsmobxmobx-react

Mobx - when to use useLocalStore hook with react-mobx


I don't get why useLocalStore hook exist. I am declaring stores outside of the React component body using the observable method imported from mobx lib.

Then, every component that uses the store in any way is wrapped into observer HOC from mobx-react.

Everything works perfectly fine, but I'm not sure whether I'm not doing something wrong because useLocalStore hook is used all over the documentation and I'm not using it.

Example with store being declared outside of the react component:

import { observable } from 'mobx'
import { observer } from 'mobx-react'

const person = observable({ name: 'John' })

const Person = observer(function Person() {
  return (
    <div>
      {person.name}
      <button onClick={() => (person.name = 'Mike')}>No! I am Mike</button>
    </div>
  )
})

Why would I use useLocalStore hook?


Solution

  • It creates a local observable that will be stable between renderings.

    You can use if with functional components. In the example, you can see that the component doesn't depend on any react context or external store, but it's still using mobx and it's completely self-contained.

    import { useObserver, useLocalStore } from 'mobx-react'
    function Person() {
      const person = useLocalStore(() => ({ name: 'John' }))
      return useObserver(() => (
        <div>
          {person.name}
          <button onClick={() => (person.name = 'Mike')}>No! I am Mike</button>
        </div>
      ))
    }