I am trying to learn how to use MobX with React, and I don't understand why using a Provider or Context is necessary, if the object that holds the state never changes, only its contents.
E.g. I have a store (a simple timer that changes over time) in store.js:
import { decorate, observable, action } from 'mobx';
import React from 'react';
class TheTimer {
currentTick = 0; // In seconds since start
tick = () => {
this.currentTick = Math.floor(performance.now() / 1000);
}
}
decorate(TheTimer, {
currentTick: observable,
tick: action
});
// Bare store
export const timerStore = new TheTimer();
// Store as React context
export const TimerStoreContext = React.createContext(timerStore);
// This makes the timer go
setInterval(timerStore.tick, 100);
Now there is no problem using the bare store in a component:
import React from 'react';
import { configure } from 'mobx';
import { observer } from 'mobx-react';
import { timerStore } from './store';
configure({ enforceActions: 'observed' });
const App = observer(() => {
return (
<p>{timerStore.currentTick}</p>
);
});
export default App;
Using the context also works:
import React from 'react';
import { configure } from 'mobx';
import { observer } from 'mobx-react';
import { TimerStoreContext } from './store';
configure({ enforceActions: 'observed' });
const App = observer(() => {
const timerStore = React.useContext(TimerStoreContext);
return (
<p>{timerStore.currentTick}</p>
);
});
export default App;
(I'm using create-react-app plus mobx, mobx-react, that is React 16.9.0 with MobX 5.13.0 and mobx-react 6.1.3)
Note that the store is created once and from then on it always stays the same object.
Why is Context used by everybody (or older mobx-react Provider based solutions) when using the store directly as a global variable also works?
Is it only about testability?
Note that I also have JS code that's not React, the application communicates over Websockets with the server and updates from the server will also lead to actions being called; I plan to use the bare store for that as that code lives outside React components.