Cecilia Mzayek
Cecilia Mzayek

Reputation: 65

When should I use a MobX observable instead of a React state variable?

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

Answers (1)

Danila
Danila

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

Related Questions