4

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?

feerlay
  • 2,286
  • 5
  • 23
  • 47
  • 1
    Try to create two components and you'll see the problem, they will share their person, unlike the answer below – mweststrate May 18 '20 at 11:19
  • Ah got it, that makes sense, because they will share the person observable. For global stuff like authentication I think it's fine to declare "stores" outside of the components - will be careful about that tho :) Thank you for mobx - it's great, I've no idea why I used redux for so long. – feerlay May 18 '20 at 14:28

2 Answers2

3

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>
  ))
}
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • Thank you for the answer. I just added an example with store being declared outside of the component. Is that wrong and not "stable between rerenders"? – feerlay May 16 '20 at 19:04
  • 1
    Everything that is outside the component is stable because it is not redeclared every time the function component runs/renders. That is also the main principle behind `React.createContenxt` – Ivan V. May 18 '20 at 10:17
0

useLocalStore has been deprecated in favor of useLocalObservable, see here.