Reputation: 65
I'm a bit confused. I usually use observables for all the variables that affect what is rendered. But is that the correct way? When should I use state instead of an observable?
Upvotes: 2
Views: 2905
Reputation: 18566
Well, it depends!
Usually you have external (shared, global or whatever you call it) state as observable
values (they are often called stores, you can make them with classes or pure object or with something else like mobx-state-tree).
And local store is handled with "default" React way such as useState
or useReducer
for functional component, or state
and setState
for classes.
But sometimes it is very convenient to use MobX for local state too, for such cases there is a hook useLocalObservable
so you can continue to write everything in MobX way:
import { observer, useLocalObservable } from "mobx-react-lite"
import { useState } from "react"
const TimerView = observer(() => {
const timer = useLocalObservable(() => ({
secondsPassed: 0,
resetTime() {
this.secondsPassed = 0
}
increaseTimer() {
this.secondsPassed++
}
}))
return <span onClick={timer.resetTimer}>Seconds passed: {timer.secondsPassed}</span>
})
Although this way might somehow interfere with React Suspense in the future, so it is not recommended for everyone unless you sure you will be fine with it. More about it here: https://mobx.js.org/react-integration.html#you-might-not-need-locally-observable-state
Upvotes: 2