12

Within the mobx-react documentation there are variations in how stores are created. For example, on the React Context page:

In the first code sample, the store is instantiated with useLocalStore:

  const store = useLocalStore(createStore)

In the second code sample, the stores are initiated by directly "newing" the stores":

  counterStore: new CounterStore(),
  themeStore: new ThemeStore(),

By inference, the first is a "local" store (and thus needs useLocalStore), and the second is a "global" store and thus doesn't. However, it is not clear why this is, and what the subsequent differnce in behaviour is.

Why is useLocalStore not needed in second example, and what difference does this make to the behavior of the stores and mobx within React?

Thanks for any input

arhnee
  • 1,044
  • 9
  • 24

3 Answers3

15

OK, I found the answer. useLocalStore turns a javascript literal into a store with observable properties. This is not needed if a store is created from a class object with observable attributes.

Thanks to @freddyc for the answer

arhnee
  • 1,044
  • 9
  • 24
4

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

M K
  • 9,138
  • 7
  • 43
  • 44
0

Links from the question are no longer valid, mobx-react docs are now here:
https://mobx.js.org/react-integration.html

useLocalObservable(initializer, annotations)

is just a shorthand for:

useState(() => observable(initializer(), annotations, {autoBind: true}))[0]

useLocalStore is almost the same, but it was deprecated because it wasn't as practical.

Why is this needed?

useState() is the main way to store a variable in React.

observable({...}) is the main way to create observable objects in Mobx.

And when using Mobx+React you'll often need the useState + observable combo, so it is nice to have a shorthand.

When is it not needed?

If you are using a class to create your store then you don't need the observable wrapper and you can simply do:

const myStore = useState(() => new MyStore())[0];

If you are using React class components you can save the store on a class field.

class MyComponent
{
   myStore = new MyStore();

   render() {...}
}

Bonus tip:

Why do we use useState for memorizing values instead of useMemo?

useMemo is meant to be used more like a cache for performance optimization, rather than for storing app state.

zoran404
  • 1,682
  • 2
  • 20
  • 37