-
-
Save wickedev/dc2189c2b25b99433452cd9f30ad1049 to your computer and use it in GitHub Desktop.
import { action, observable } from 'mobx' | |
import { MobXProviderContext, observer, Provider } from 'mobx-react' | |
import React, { useContext } from 'react' | |
class CounterViewModel { | |
@observable count: number = 0 | |
@action.bound public plus() { | |
this.count++ | |
} | |
@action.bound public minus() { | |
this.count-- | |
} | |
} | |
export function App() { | |
return ( | |
<Provider counter={new CounterViewModel()}> | |
<Counter /> | |
</Provider> | |
) | |
} | |
const Counter = observer(() => { | |
const { counter }: { counter: CounterViewModel } = useContext( | |
MobXProviderContext, | |
) | |
return ( | |
<div> | |
<div>{counter.count}</div> | |
<button onClick={counter.minus}>-</button> | |
<button onClick={counter.plus}>+</button> | |
</div> | |
) | |
}) |
@jaeyow I changed my code to explain something for a moment. MobXProviderContext
can be used with the above code when mixing legacy mobx-react Provider
and class component with @inject
. If you use only the function component, you can use Context API directly without MobXProviderContext. https://github.com/mobxjs/mobx-react#provider-and-inject
thanks for that @wickedev. still getting my head around mobx, specially with the nuances of legacy vs current version. i know that the above example is trivial, however i struggle to understand the value that mobx brings to the table, for example, the above code can be easily done just with vanilla react and context api. maybe you can point me to a resource to help me understand this? or care to explain a bit?
@jaeyow If you want to introduce mobx for the first time, you don't have to care about the legacy mobx-react Provider. It was because of the performance problem that react team removed the legacy Context from core and introduced the new Context API. MobXProviderContext is an effort by mobx maintainers to ensure backward compatibility while using the Context API internally.
I'm confused about MobXProviderContext. Where is it actually used? I though we didn't have to create ConunterContext ourselves?