2
votes

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?

1
Try to create two <Person> components and you'll see the problem, they will share their person, unlike the answer below - mweststrate
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

1 Answers

3
votes

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>
  ))
}