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>
)
})
@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