reactjsmobxmobx-reactmobx-react-lite

Mobx. Getting value from another store


I have Mobx FirstStore and import SecondStore. SecondStore has a (value) and I want to use it (value) in my FirstStore.

As shown in the screenshots, this is how it works, but I have a question, is it safe to use it? If (value) changes in my SecondStore, will FirstStore see it?

Perhaps it is better to add a parameter and pass (value) through the React component when calling the function?

async someFetchRequest(valueFromSecondStore) {
  await api.retData(valueFromSecondStore)
}

Thanks in advance!

enter image description here

======================================================================================

enter image description here


Solution

  • It is totally fine to use it like that in most cases.

    There are cases when you might consider different approaches like Dependency Injection, or just pass values as parameters like you said. But until you encounter those advanced scenarios (make testing more approachable, for example, or server side rendering) you can safely use it like that. You can even make computed getter in the FirstStore, or reaction, with some value from the SecondStore and it will work as expected.

    You can also encounter circular dependency loop in some rare cases if you import class A to class B and class B to class A, but if you only import them one way you are fine.