React MobX – reading values from store outside of components

I wanted to use MobX in my new project for the first time and still don’t understand everything.

I have store like this:

function createStore() {
  return makeAutoObservable({
    value: null,
    setValue(newVal) {
      this.value = newVal
    }
  })
}
const store = createStore();
export default store;

It works if I use value from store in component like this (after import it in component’s file):

function Component() {
  return <p>{store.value}</p>
}

In my app there is a lot of places where I need use value in functions defined outside of components (like some fetch requests).

My question is: can I call store.value directly in function like this (without any possible problems):

// import store
const fn = () => {
  const val = store.value;
  // do something with it and return
}

Or should I always use store values in components with observer and then pass value to fn function as argument?

Leave a Comment