Skip to content

Instantly share code, notes, and snippets.

@wickedev
Last active March 21, 2020 10:34
Show Gist options
  • Save wickedev/dc2189c2b25b99433452cd9f30ad1049 to your computer and use it in GitHub Desktop.
Save wickedev/dc2189c2b25b99433452cd9f30ad1049 to your computer and use it in GitHub Desktop.
MobXProviderContext sample
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
Copy link

jaeyow commented Mar 21, 2020

I'm confused about MobXProviderContext. Where is it actually used? I though we didn't have to create ConunterContext ourselves?

@wickedev
Copy link
Author

wickedev commented Mar 21, 2020

@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

@jaeyow
Copy link

jaeyow commented Mar 21, 2020

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?

@wickedev
Copy link
Author

wickedev commented Mar 21, 2020

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment